Pandas/matplotlib 条形图,颜色由列定义 [英] Pandas/matplotlib bar chart with colors defined by column

查看:51
本文介绍了Pandas/matplotlib 条形图,颜色由列定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中制作条形图,并通过数据框列制作颜色条,这在 R ggplot2 中非常容易,所以我真的不明白为什么它在 matplotlib/pandas 中如此困难,我会喜欢了解如何做到这一点,并希望我认为的逻辑毕竟不难

I am trying to make a bar chart in python, and color bars by a data frame column, this is exceedingly easy in R ggplot2, so I really do who not understand why it is so hard in matplotlib/pandas, I would like to understand how to do it and hopefully the logic as I assume it can't be hard after all

这是我想要的例子.我在 ggplot 中做了 - 我想要的只是使用数据框中的属性定义颜色,属性可以是颜色字符串,即 'k','r' .. 或数据的一个特征,比如男性/女性等.

Here is an example of what I want. I did in ggplot - all I want is to define the color using attributes in the data frame, the attribute can be the color string i.e. 'k','r' .. or a feature of the data say male/female, etc.

这是我尝试生成条形的代码示例

this is an example of code I tried that works to generate the bars

import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame({'name' : ['a','b','c'],'value' : [1,2,3], 
                     'c' : ['b','r','b']})
data.plot('name','value',kind='bar')

但是我想要由列'c'定义的颜色

but I want the color defined by column 'c'

但是当我添加 color='c' 时它不起作用

but when I add color='c' then it does not work

data.plot('name','value',color='c',kind='bar',color='c')

我也尝试使用plot.scatter,但是也没有用

I tried using plot.scatter as well and it did not work either

----更新

我做了更多的工作,或多或少地起作用了,我还没有弄清楚如何正确对齐标签,我仍然喜欢为什么我必须有一个数字x轴,当它确实是绝对的时(再次)ggplot2自行处理)-但至少可以用代码完成

I did some more work and this works more or less, I have yet to figure out how to properly align the labels, I still do to like why I have to have a numeric x axis, when it is really categorical (again ggplot2 deals with this on its own) - but ar least this can be done in code

fig, ax = plt.subplots()
ax.bar(range(len(data)),data['value'],width=.5,color=data['c'])
ax.set_xticks(range(len(data)))
ax.set_xticklabels( (data['name'] ))

一如既往的感谢

推荐答案

尝试一下:

data.plot('name','value',color=['r', 'g', 'b'],kind='bar')

您可以将颜色的任意组合作为列表提供给color参数.如果条数多于颜色数,则颜色会循环使用.

You can give any combination of colors as a list to the color argument. If there are more bars than number of colors, the colors will just recycle.

我还可以强烈推荐优秀的 brewer2mpl 库.它提供了美观的颜色选择.代码如下所示:

I can also strongly recommend the excellent brewer2mpl library. It provides aesthetically pleasing color choices. The code looks like this:

import brewer2mpl
bmap = brewer2mpl.get_map('Set2','qualitative',3,reverse=True)
colors = bmap.mpl_colors
data.plot('name','value',color=colors,kind='bar')

导致:

您可以从这里获取 brewer2mpl:https://pypi.python.org/pypi/brewer2mpl/1.4

You can get brewer2mpl from here: https://pypi.python.org/pypi/brewer2mpl/1.4

这篇关于Pandas/matplotlib 条形图,颜色由列定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆