【发布时间】:2015-09-13 12:01:14
【问题描述】:
我正在尝试创建一个条形图,其中所有小于最大的条都是一些平淡的颜色,而最大的条是更鲜艳的颜色。一个很好的例子是黑马分析的pie chart gif,他们在其中分解了一个饼图并以更清晰的条形图结束。任何帮助将不胜感激,谢谢!
【问题讨论】:
我正在尝试创建一个条形图,其中所有小于最大的条都是一些平淡的颜色,而最大的条是更鲜艳的颜色。一个很好的例子是黑马分析的pie chart gif,他们在其中分解了一个饼图并以更清晰的条形图结束。任何帮助将不胜感激,谢谢!
【问题讨论】:
只需传递一个颜色列表。类似的东西
values = np.array([2,5,3,6,4,7,1])
idx = np.array(list('abcdefg'))
clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
sb.barplot(x=idx, y=values, palette=clrs) # color=clrs)
(正如 cmets 中指出的,Seaborn 的更高版本使用“调色板”而不是“颜色”)
【讨论】:
color=关键字必须替换为palette=
其他答案定义了 之前 绘图的颜色。您也可以之后通过更改条本身来做到这一点,它是您用于绘图的轴的补丁。重新创建 iayork 的示例:
import seaborn
import numpy
values = numpy.array([2,5,3,6,4,7,1])
idx = numpy.array(list('abcdefg'))
ax = seaborn.barplot(x=idx, y=values) # or use ax=your_axis_object
for bar in ax.patches:
if bar.get_height() > 6:
bar.set_color('red')
else:
bar.set_color('grey')
您也可以直接通过例如ax.patches[7]。使用dir(ax.patches[7]),您可以显示可以利用的 bar 对象的其他属性。
【讨论】:
[Barplot case] 如果您从数据框中获取数据,您可以执行以下操作:
labels = np.array(df.Name)
values = np.array(df.Score)
clrs = ['grey' if (x < max(values)) else 'green' for x in values ]
#Configure the size
plt.figure(figsize=(10,5))
#barplot
sns.barplot(x=labels, y=values, palette=clrs) # color=clrs)
#Rotate x-labels
plt.xticks(rotation=40)
【讨论】:
我是如何做到的:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
bar = sns.histplot(data=data, x='Q1',color='#42b7bd')
# you can search color picker in google, and get hex values of you fav color
patch_h = []
for patch in bar.patches:
reading = patch.get_height()
patch_h.append(reading)
# patch_h contains the heights of all the patches now
idx_tallest = np.argmax(patch_h)
# np.argmax return the index of largest value of the list
bar.patches[idx_tallest].set_facecolor('#a834a8')
#this will do the trick.
我喜欢通过读取最大值来设置之前或之后的颜色。我们不必担心补丁的数量或最高值是多少。 参考matplotlib.patches.Patch ps:我对这里给出的情节进行了更多的定制。上面给出的代码不会产生相同的结果。
【讨论】: