不同颜色的熊猫绘图栏无法正常工作

时间:2018-09-01 01:51:59

标签: python pandas matplotlib

我试图绘制一个条形图,前10条为绿色,后10条为红色。

这是我的代码:

import pandas as pd
import numpy as np

df = pd.DataFrame({'c0':np.arange(20)})

my_colors = ['g','g','g','g','g',
             'g','g','g','g','g',
             'r','r','r','r','r',
             'r','r','r','r','r']
df.plot(kind='bar', color=my_colors)

enter image description here

该如何解决?

pd.__version__
'0.23.4'

2 个答案:

答案 0 :(得分:3)

颜色必须是包含列表的列表。 尝试:

df = pd.DataFrame({'c0':np.arange(20)})

# attention to double "["
my_colors = [['g','g','g','g','g',
              'g','g','g','g','g',
              'r','r','r','r','r',
              'r','r','r','r','r']]

df.plot(kind='bar', color=my_colors)

enter image description here

还有this问题也可以帮助

答案 1 :(得分:0)

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

df = pd.DataFrame({'c0':np.arange(20)})

my_colors = ['g','g','g','g','g',
             'g','g','g','g','g',
             'r','r','r','r','r',
             'r','r','r','r','r']
for i ,row in enumerate(my_colors):
    plt.bar(i,df.loc[i,"c0"],color=row)

enter image description here