【问题标题】:bar plot with different colors in pythonpython中不同颜色的条形图
【发布时间】:2015-10-07 21:13:07
【问题描述】:

我有这样的数据:

import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)

我想用不同颜色的水平条绘制数据框,以参考列'typ'

【问题讨论】:

  • 也许对另一个matplotlib question 的接受答案可能会对您有所帮助:它循环遍历各个条(补丁)并为每个补丁单独分配颜色。您需要将其用于条形图。

标签: python-2.7 pandas matplotlib


【解决方案1】:

可以使用matplotlib的barh函数的color参数:

import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)

# define the colors for each type
colors = {1:'blue', 2:'red'}

# plot the bars
plt.bar(range(len(df)), df['value'], align='center',
        color=[colors[t] for t in df['typ']])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多