如何使用来自多个数据框的数据绘制分组柱状图

huangapple go评论60阅读模式
英文:

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

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)
英文:
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 of fmt= 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)

huangapple
  • 本文由 发表于 2023年5月29日 01:28:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定