简体   繁体   English

尝试向Matplotlib图表添加颜色渐变

[英]Trying to add color gradients to Matplotlib chart

I am trying to add a red to green color gradient for my charts. 我正在尝试为图表添加红色到绿色的渐变。 When I run the the following however, I get: 但是,当我运行以下代码时,我得到:

TypeError: object of type 'Color' has no len()

Here is the piece of relevant code: 这是相关代码:

from colour import Color

red = Color("red")
colors = list(red.range_to(Color("green"),10))

for col in ['DISTINCT_COUNT', 'NULL_COUNT','MAX_COL_LENGTH', 'MIN_COL_LENGTH']: 
    grid[['COLUMN_NM', col]].set_index('COLUMN_NM').plot.bar(title=table_nm, figsize=(12, 8), color=colors)
    plt.xlabel('Column', labelpad=12)
    plt.tight_layout()
    plt.show()

If I just run the top portion and print the results, it seems to run fine: 如果我只运行顶部并打印结果,它似乎运行良好:

red = Color("red")
colors = list(red.range_to(Color("green"),10))
print(colors)

[<Color red>, <Color #f13600>, <Color #e36500>, <Color #d58e00>, <Color #c7b000>, <Color #a4b800>, <Color #72aa00>, <Color #459c00>, <Color #208e00>, <Color green>]

So it must be when I am trying to use it here: 所以一定是当我尝试在这里使用它时:

grid[['COLUMN_NM', col]].set_index('COLUMN_NM').plot.bar(title=table_nm, figsize=(12, 8), color=colors)

Any ideas? 有任何想法吗?

Matplotlib cannot work with colour.Color instances. Matplotlib无法使用colour.Color实例。 You may convert those to RGB values if you like. 如果愿意,可以将它们转换为RGB值。

Next, pandas does not like to be given several colors. 其次,熊猫不喜欢被赋予几种颜色。 But you may use a matplotlib plot instead. 但是您可以改用matplotlib图。

import matplotlib.pyplot as plt
import pandas as pd
from colour import Color

df = pd.DataFrame({"x" : list(range(3,13))})

red = Color("red")
colors = list(red.range_to(Color("green"),10))
colors = [color.rgb for color in colors]

plt.bar(df.index, df["x"], color=colors)
plt.xlabel('Column', labelpad=12)
plt.tight_layout()
plt.show()

在此处输入图片说明

Note that usually you would rather work with a colormap. 请注意,通常您宁愿使用颜色图。 You may call this colormap with the normalized values according to which you want to colorize your bars. 您可以使用要为条形着色所依据的归一化值来调用此颜色图。

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

df = pd.DataFrame({"x" : np.random.rand(10)*10})

cmap = mcolors.LinearSegmentedColormap.from_list("", ["red", "yellow", "green"])

plt.bar(df.index, df["x"], color=cmap(df.x.values/df.x.values.max()))
plt.xlabel('Column', labelpad=12)
plt.tight_layout()
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM