我有以下数据框:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df_One = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
'Qtd_Instrumentation': [18, 5, 25, 10]})
df_Two = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
'Qtd_Instrumentation': [14, 1, 22, 10]})
我想构建一个条形图,其中包含来自两个数据框的信息,即蓝色条表示datadrame_One,垂直的红色条表示dataframe_Two的信息。
我尝试如下实现:
fig, ax = plt.subplots()
n_group = len(df_One['Category'])
index = np.arange(n_group)
bar_width = 0.35
opacity = 0.8
rects1 = df_One.plot.bar(x='Category', y='Qtd_Instrumentation', color='r', label = 'Station
One')
rects2 = df_Two.plot.bar(x='Category', y='Qtd_Instrumentation', color='b', label = 'Station
Two')
plt.xlabel('Category Instrumentation')
plt.ylabel('Qtd Instrumentation')
plt.show()
但是,此代码是错误的,因为它设计了两个条形图,而不是仅使用两个表示来构建一个图。
有谁知道我可以如何构建此描述的图表?ks
这是一种选择方法,选择一个align='edge'
选项,然后对一个条使用正宽度,对另一条使用负宽度。这将使它们彼此对齐。另外,您必须致电plt.legend()
以显示图例
fig, ax = plt.subplots()
index = np.arange(len(df_One['Category']))
bar_width = 0.35
opacity = 0.8
ax.bar(index, df_One['Qtd_Instrumentation'], color='r', align='edge', width=bar_width, label = 'Station One')
ax.bar(index, df_Two['Qtd_Instrumentation'], color='b', align='edge', width=-bar_width,label = 'Station Two')
# Assign the tick labels
ax.set_xticks(index)
ax.set_xticklabels(df_One['Category'], rotation=90)
plt.xlabel('Category Instrumentation')
plt.ylabel('Qtd Instrumentation')
plt.legend()
plt.show()
另一种方法是通过使用关键字以下position
放置杆彼此相邻,如图这里
df_One.Qtd_Instrumentation.plot(kind='bar', color='red', ax=ax, width=bar_width, position=1)
df_Two.Qtd_Instrumentation.plot(kind='bar', color='blue', ax=ax, width=bar_width, position=0)
ax.set_xlim(-0.5, 3.5)
ax.set_xticks(index)
ax.set_xticklabels(df_One['Category'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句