如何用渐变色着色MatPlotLib图形

2024-10-04 09:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中用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

我找不到这方面的任何信息。在


Tags: thetotruebyreturnmatplotlibformatternp
1条回答
网友
1楼 · 发布于 2024-10-04 09:24:47

看看matplotlib文档中的^{}示例。在

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

你应该在上面的例子中找到一个简化版本。它使用Excel示例中的值,以及使用CSS colors“道奇蓝”和“皇家蓝”作为线性渐变的颜色贴图。在

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()

相关问题 更多 >