仅使用pandas dataframeplot
方法,如何绘制条形图以绘制不同的颜色?
如果我有此DataFrame:
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
index count
0 0 3372
1 1 68855
2 2 17948
3 3 708
4 4 9117
df.plot()
我需要设置哪些参数,以便绘图中的每个条形:
我正在尝试:
df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False)
结果:
我已经知道的(是的,这可行,但是我的目的是弄清楚如何df.plot
仅使用此方法。肯定有可能吗?):
def f(df):
groups = df.groupby('index')
for name,group in groups:
plt.bar(name, group['count'], label=name, align='center')
plt.legend()
plt.show()
您没有可以传递给df.plot
它的参数来使单个列的条形着色不同。
由于不同列的条形颜色不同,因此可以选择在绘制之前转置数据框,
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
现在,这会将数据绘制为子组的一部分。因此,需要进行一些调整才能正确设置限制和xlabel。
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()
虽然我猜想此解决方案符合问题的标准,但使用确实没有错plt.bar
。一个电话plt.bar
就足够了
plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))
完整的代码:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()
plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句