Py学习  »  Python

如何在python中为dataframe列中的唯一条目绘制条形图?

Alenson Toh • 5 年前 • 1470 次点击  

我这里有一个数据帧,有两个唯一的时间窗口 df_mo4['time_window'] , 2018-09-26 11:30:00 2018-09-26 11:32:30 2018-09-26 11:32:30 2018-09-26 11:35:00 . 我想绘制两组柱状图(不是子块),其中第一个柱状图在一个时间窗口中表示单个id的平均时间、最大时间和最小时间,而下一个柱状图在另一个时间窗口中表示相同的数据,对此我该怎么办?另外,我希望标题像持续时间(时间窗口)。谢谢您!

df.plot(kind='bar')
plt.title('Duration \n {}'.format(df['time_window']))
plt.ylabel('Time (s)')
plt.xlabel('ID')
plt.legend(['Mean Time (s)', 'Minimum Time (s)', 'Maximum Time (s)'], loc='upper right')
plt.xticks(np.arange(len(df['ID'])), df['ID'], fontsize=5)
plt.show()

样本数据:

       ID  time_window                         mean_time   min_time    max_time 
0  8027  2018-09-26 11:30:00 to 2018-09-26 11:32:30  0.101679 0.056412 0.340988
1  8027  2018-09-26 11:32:30 to 2018-09-26 11:35:00  0.090957 0.052196 0.323442
2  8028  2018-09-26 11:30:00 to 2018-09-26 11:32:30  0.199167 0.076872 0.614797       
3  8028  2018-09-26 11:32:30 to 2018-09-26 11:35:00  0.239885 0.062660 0.590710     
4  8029  2018-09-26 11:30:00 to 2018-09-26 11:32:30  0.243241 0.098516 0.5713      
5  8030  2018-09-26 11:30:00 to 2018-09-26 11:32:30  0.083064 0.055656 0.27892       
6  8031  2018-09-26 11:32:30 to 2018-09-26 11:35:00  0.134786 0.058290 0.51279        
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41196
 
1470 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Horbaje
Reply   •   1 楼
Horbaje    6 年前

这是我可以建议您的代码:

#Read your Dataframe
df = pd.read_csv('Test.csv', index_col=None, header='infer', encoding="utf-8-sig")

#split the time_window column into two columns, so you can calculate Duration
df['start_time'], df['end_time'] = df['time_window'].str.split('to', 1).str

#convert start and ending time columns to datetime and ID to numeric
df[['start_time','end_time']] = df[['start_time','end_time']].apply(pd.to_datetime, format='%Y-%m-%d %H:%M:%S')
df["ID"] = pd.to_numeric(df["ID"])

#Calculate the duration of a time window and convert into seconds
df['Duration'] = df['start_time'] - df['end_time']
df['Duration']=df['Duration']/np.timedelta64(1,'s')

#plot 
ax = df.plot(x="ID", y=["min_time", "max_time", "mean_time"], kind="bar", rot=25)
ax.set_xlabel("Instances (ID)")
ax.set_ylabel("Duraction(s)")
ax.set_title("Visualization")

rects = ax.patches
labels = df['Duration']

for rect, label in zip(rects, labels):
     height = rect.get_height()
     ax.text(rect.get_x() + rect.get_width(), height+0.3, label,
             ha='center', va='bottom')

这将生成以下数据帧和图。

enter image description here

enter image description here

这就是你要找的吗?你说你不想要子块,但听起来你也希望每个id都有一个单独的图表?