Reputation: 3801
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?
Upvotes: 3
Views: 5626
Reputation: 339180
Matplotlib cannot work with colour.Color
instances. You may convert those to RGB values if you like.
Next, pandas does not like to be given several colors. But you may use a matplotlib plot instead.
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()
Upvotes: 6