2017-03-06 314 views
0

我有蟒蛇我已经和matplotlib用下面的代码的图形:如何着色MatPlotLib图形使用渐变色

def to_percent(y, position): 
    s = str(250 * y) 
    if matplotlib.rcParams['text.usetex'] is True: 
     return s + r'$\%$' 
    else: 
     return s + '%' 

distance = df['Distance'] 
perctile = np.percentile(distance, 90) # claculates 90th percentile 
bins = np.arange(0,perctile,2.5) # creates list increasing by 2.5 to 90th percentile 
plt.hist(distance, bins = bins, normed=True) 
formatter = FuncFormatter(to_percent) #changes y axis to percent 
plt.gca().yaxis.set_major_formatter(formatter) 
plt.axis([0, perctile, 0, 0.10]) #Defines the axis' by the 90th percentile and 10%Relative frequency 
plt.xlabel('Length of Trip (Km)') 
plt.title('Relative Frequency of Trip Distances') 
plt.grid(True) 
plt.show() 

enter image description here

我想知道的是什么,是可以使用渐变而不是块颜色对条进行着色,就像在Excel中的这张图片中一样。

enter image description here

我已经无法找到这方面的消息。

+0

不用调用'hist',你可以使用'numpy.histogram'并用'bar'绘图。然后[文档示例](http://matplotlib.org/examples/pylab_examples/gradient_bar.html)将适用。 – wflynny

+0

[如何用渐变填充matplotlib栏?]可能重复(http://stackoverflow.com/questions/38830250/how-to-fill-matplotlib-bars-with-a-gradient) – wflynny

回答

1

查看matplotlib文档中的gradient_bar.py示例。

基本思想是,您不使用pyplot中的hist()方法,而是使用imshow()来代替自己构建条形图。 imshow()的第一个参数包含将显示在由extent指标指定的框内的颜色映射。

下面是上面引用的例子的一个简化版本,它可以帮助您走上正轨。它使用Excel示例中的值以及使用CSS colors'dodgerblue'和'royalblue'作为线性渐变的颜色映射。

from matplotlib import pyplot as plt 
from matplotlib import colors as mcolors 

values = [22, 15, 14, 10, 7, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1, 7] 

# set up xlim and ylim for the plot axes: 
ax = plt.gca() 
ax.set_xlim(0, len(values)) 
ax.set_ylim(0, max(values)) 

# Define start and end color as RGB values. The names are standard CSS color 
# codes. 
start_color = mcolors.hex2color(mcolors.cnames["dodgerblue"]) 
end_color = mcolors.hex2color(mcolors.cnames["royalblue"]) 

# color map: 
img = [[start_color], [end_color]] 

for x, y in enumerate(values): 
    # draw an 'image' using the color map at the 
    # given coordinates 
    ax.imshow(img, extent=(x, x + 1, 0, y)) 

plt.show()