【问题标题】:How to make DataFrame plot bars be shown in different colors?如何使 DataFrame 绘图条以不同的颜色显示?
【发布时间】:2021-05-31 13:04:21
【问题描述】:

我是一名新手数据分析师,我正在尝试使用 df.plot() 创建一个数据框条形图,以便条形具有不同的颜色。我发现除非数据帧被转置,否则没有任何参数可以传递给不同颜色的条形图。我尝试使用以下代码对其进行转置:

gender_overview = pd.read_sql("SELECT Gender, COUNT(*) AS NumberOfPeople "
                          "FROM [AdventureWorks2019].[Sales].[vPersonDemographics] "
                          "GROUP BY Gender "
                          "ORDER BY NumberOfPeople DESC;", conn)

display(gender_overview)
df = gender_overview.set_index('Gender')
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
labels = ['Male', 'Female', 'Not Specified']
ax.set_xticks(range(len(df)))
ax.set_xticklabels(labels=labels, rotation=0)
plt.show()

然而,bar 和 x_ticks 最终是不匹配的(请看截图 here.)

如何确保条形图与相应的 x_ticks 匹配?

提前感谢您的帮助:)

【问题讨论】:

  • 我很难相信您必须转置 DF。尝试不使用,我只是这样做了,它没有抱怨。

标签: pandas dataframe matplotlib plot bar-chart


【解决方案1】:

我发现当我想要一些精细控制时,我无法使用 Pandas 进行绘图。我倾向于使用 matplotlib。

import panda as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame()
df['test'] = np.arange(6)
df['gender'] = ['M', 'F', 'F', 'M', 'F', 'F']
df.set_index('gender', inplace=True)

plt.bar(df.index, df['test'], color=['blue', 'red'])
plt.show()

尝试 group-by 很诱人,但我认为它没有帮助。

g = df.groupby("gender").count()
plt.bar(g.index, g['test'], color=['blue', 'red'])
plt.show()

【讨论】:

  • 成功了!非常感谢您的建议!使用 Matplotlib 真的容易得多
  • 太好了。 Matplotlib 来自 MATLAB 有点令人困惑,但最终它是有意义的。
猜你喜欢
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多