英文:
How to plot a grouped bar plot with data from multiple dataframes
问题
以下是您的代码的翻译部分:
import pandas as pd
import matplotlib.pyplot as plt
Type_X = [200000, 150000]
Type_Y = [168000, 120000]
Comb = [192000]
Cat = ['有时间限制', '有生产限制']
Cat2 = ['设备优化组合']
df = pd.DataFrame({'类型 X': Type_X, '类型 Y': Type_Y}, index=Cat)
df2 = pd.DataFrame({'组合': Comb}, index=Cat2)
print(df)
print(df2)
ax = plt.subplots()
df.plot.barh(figsize=(15, 8), color={"类型 X": "lightblue", "类型 Y": "purple"})
df2.plot.barh(figsize=(15, 8), color={'组合': 'green'})
# 在条形图中注释条形
for container in ax.containers:
ax.bar_label(container)
plt.title('不同约束下设备的每周利润', fontdict={'fontsize': 20,
'fontweight': 'bold',
'color': 'black',
'verticalalignment': 'baseline',
'horizontalalignment': 'center'})
# 导出文件
# plt.savefig("SEC_Weekly_Profit_Cons", dpi=300)
# 隐藏右侧和顶部边框
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# 显示图表
plt.show()
请注意,我已将图表的标签翻译为中文,但其他部分保持原样。希望这对您有所帮助!
英文:
how to plot multiple categories with different data lengths on the same bar chart in python?
Here is my code:
import pandas as pd
import matplotlib.pyplot as plt
Type_X = [200000, 150000]
Type_Y = [168000, 120000]
Comb = [192000]
Cat = ['With Time Constraints', 'With Production Constraints']
Cat2 = ['Optimised Combination of Devices']
df = pd.DataFrame({'Type X': Type_X,
'Type Y': Type_Y,}, index=Cat)
df2 = pd.DataFrame({'Comb' : Comb}, index=Cat2)
print(df)
print(df2)
ax = plt.subplots()
df.plot.barh(figsize = (15, 8), color={"Type X": "lightblue", "Type Y": "purple"})
df2.plot.barh(figsize = (15, 8), color={'Comb' : 'green'})
#annotate bars in bar plot
for container in ax.containers:
ax.bar_label(container)
plt.title('SEC Weekly Profits of Devices under different Constraints', fontdict = {'fontsize': 20,
'fontweight': 'bold',
'color': 'black',
'verticalalignment': 'baseline',
'horizontalalignment': 'center'})
# export the file
# plt.savefig("SEC_Weekly_Profit_Cons", dpi = 300)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# plot show
plt.show()
Here is the kind of chart I expect to see:
答案1
得分: 0
-
最简单的实现方法是使用
pd.concat
来合并数据帧。 -
参考文献:
- 如何从绘图中删除 x 轴刻度
- 如何将图例放在图外
- 如何在柱状图上添加数值标签
- 从
matplotlib 3.7.0
开始,可以使用fmt=
来筛选和自定义标签。 - 在
matplotlib 3.7.0
之前,自定义标签应使用列表推导和labels=
。
- 从
-
在
python 3.11.3
、pandas 2.0.1
、matplotlib 3.7.1
中测试通过
import pandas as pd
df1 = pd.DataFrame({'Type X': Type_X, 'Type Y': Type_Y}, index=Cat)
df2 = pd.DataFrame({'Comb': Comb}, index=Cat2)
# 合并数据帧
df = pd.concat([df1, df2], axis=1)
# 颜色字典
color = {'Type X': 'lightblue', 'Type Y': 'purple', 'Comb': 'green'}
# 绘图
ax = df.plot(kind='barh', color=color, figsize=(9, 5))
# 在条形图中标注条形
for c in ax.containers:
ax.bar_label(c, fmt=lambda w: f'{round(w):,}' if w > 0 else '')
# 隐藏右侧和顶部刻度线
ax.spines[['top', 'right', 'bottom']].set_visible(False)
# 移动图例的位置
ax.legend(loc='lower center', bbox_to_anchor=(0.5, -0.2), frameon=False, ncols=3)
# 移除刻度标记
plt.tick_params(axis='x', which='both', bottom=False)
df
Type X Type Y Comb
With Time Constraints 200000.0 168000.0 NaN
With Production Constraints 150000.0 120000.0 NaN
Optimised Combination of Devices NaN NaN 192000.0
对于 matplotlib < v3.7.0
- 应使用
labels=
而不是fmt=
。
for c in ax.containers:
labels = [f'{round(w):,}' if (w := v.get_width()) > 0 else '' for v in c]
ax.bar_label(c, labels=labels)
英文:
- The easiest implementation is to combine the dataframes with
pd.concat
- References:
- How to remove xticks from a plot
- How to put the legend outside the plot
- How to add value labels on a bar chart
- From
matplotlib 3.7.0
,fmt=
may be used to filter and customize the labels. - Prior to
matplotlib 3.7.0
, custom labels should use a list comprehension andlabels=
.
- From
- Tested in
python 3.11.3
,pandas 2.0.1
,matplotlib 3.7.1
import pandas as pd
df1 = pd.DataFrame({'Type X': Type_X, 'Type Y': Type_Y,}, index=Cat)
df2 = pd.DataFrame({'Comb' : Comb}, index=Cat2)
# combined dataframe
df = pd.concat([df1, df2], axis=1)
# color dict
color = {'Type X': 'lightblue', 'Type Y': 'purple', 'Comb': 'green'}
# plot
ax = df.plot(kind='barh', color=color, figsize=(9, 5))
# annotate bars in bar plot
for c in ax.containers:
ax.bar_label(c, fmt=lambda w: f'{round(w):,}' if w > 0 else '')
# Hide the right and top spines
ax.spines[['top','right', 'bottom']].set_visible(False)
# relocate the legend
ax.legend(loc='lower center', bbox_to_anchor=(0.5, -0.2), frameon=False, ncols=3)
# remove the tick marks
plt.tick_params( axis='x', which='both', bottom=False)
df
Type X Type Y Comb
With Time Constraints 200000.0 168000.0 NaN
With Production Constraints 150000.0 120000.0 NaN
Optimised Combination of Devices NaN NaN 192000.0
For matplotlib < v3.7.0
labels=
instead offmt=
should be used.
for c in ax.containers:
labels = [f'{round(w):,}' if (w := v.get_width()) > 0 else '' for v in c]
ax.bar_label(c, labels=labels)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论