更新时间:2023-01-28 12:01:45
没有可传递给df.plot
的参数,该参数对单个列的柱形着色不同.
由于不同列的条的颜色不同,因此一种选择是在绘制之前转置数据框,
There is no argument you can pass to df.plot
that colorizes the bars differently for a single column.
Since bars for different columns are colorized differently, an option is to transpose the dataframe before plotting,
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
现在这会将数据绘制为子组的一部分.因此,需要进行一些调整才能正确设置限制和xlabel.
This would now draw the data as part of a subgroup. Therefore some tweaking needs to be applied to set the limits and xlabels correctly.
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
就足够了
While I guess this solution matches the criteria from the question, there is actually nothing wrong with using plt.bar
. A single call to plt.bar
is sufficient
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()