matplotlib中使用颜色图的条形图 [英] Bar chart in matplotlib using a colormap

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

问题描述

我有一个包含两列的df:

I have a df with two columns:

  • y:y轴的不同数值
  • days:四个不同天的名称(星期一、星期二、星期三、星期四)

我还有一个我自己制作的包含四种不同颜色的颜色图,它是一个 ListedColorMap 对象.

I also have a colormap with four different colors that I made myself and it's a ListedColorMap object.

我想创建一个条形图,其中 x 轴为四个类别(星期几),y 轴为它们对应的值.同时,我希望每个色条都使用我的颜色图具有不同的颜色.

I want to create a bar chart with the four categories (days of the week) in the x axis and their corresponding values in the y axis. At the same time, I want each bar to have a different color using my colormap.

这是我用来构建条形图的代码:

This is the code I used to build my bar chart:

def my_barchart(my_df, my_cmap):
  fig = plt.figure()
  ax = fig.add_axes([0,0,1,1])
  ax.bar(my_df['days'], my_df['y'], color=my_cmap)
  return fig

但是,我收到以下错误:'ListedColormap' 类型的对象没有 len()",所以我似乎没有正确使用 my_cmap.

However, I get the following error: "object of type 'ListedColormap' has no len()", so it seems that I'm not using my_cmap correctly.

如果我从函数中删除它并运行它,则我的条形图看起来还可以,只是所有条形都具有相同的颜色.所以我的问题是:将颜色图与条形图一起使用的正确方法是什么?

If I remove that from the function and run it, my bar chart looks ok, except that all bars have the same color. So my question is: what is the right way to use a colormap with a bar chart?

推荐答案

好的,我找到了一种无需缩放值的方法:

Okay, I found a way to do this without having to scale my values:

def my_barchart(my_df, my_cmap):
  fig = plt.figure()
  ax = fig.add_axes([0,0,1,1])
  ax.bar(my_df['days'], my_df['y'], color=my_cmap.colors)
  return fig

只需在 my_cmap 工作后添加 .colors 即可!

Simply adding .colors after my_cmap works!

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

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