python中matplotlib绘制图形的颜色问题

lsmepo6l  于 2023-02-09  发布在  Python
关注(0)|答案(1)|浏览(196)

我试图绘制一个二分图来突出两个排名之间的差异。我这样做是通过用彩色箭头将左边列表中的城市与右边列表中的同一个城市连接起来。颜色应该与排名的差异成正比。
以下是MWE:

import matplotlib.pyplot as plt

# Sample data
cities = ['City A', 'City B', 'City C', 'City D', 'City E',
          'City F', 'City G', 'City H', 'City I', 'City J']
genepy_rank = [3, 1, 4, 2, 5, 8, 7, 10, 9, 6]
fitness_rank = [7, 9, 2, 5, 4, 6, 3, 1, 8, 10]

# Calculate the difference in ranking
diff_rank = [genepy - fitness for genepy, fitness in zip(genepy_rank, fitness_rank)]

# Plot the graph
fig, ax = plt.subplots()
for i, city in enumerate(cities):
    x = [genepy_rank[i], fitness_rank[i]]
    y = [i, i]
    color = diff_rank[i]
    ax.plot(x, y, color=color, marker='o')
    ax.annotate(city, (x[0], y[0]), xytext=(-20, 20),
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
ax.set_xlim(0, 11)
ax.set_ylim(-1, 11)
ax.set_yticks([i for i in range(len(cities))])
ax.set_yticklabels(cities)
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.show()

问题是,它会退出并显示错误:值错误:-4不是我所理解的颜色的有效值。是否有方法确定颜色网格并根据diff_rank为箭头分配颜色?
谢谢

oxcyiej7

oxcyiej71#

与其指定颜色,为什么不使用色彩Map表呢?
如果您还想显示一个颜色条(如我所做的),请记住plt.plot不提供示例化颜色条所必需的ScalarMappable,因此您必须提供一个。

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import BoundaryNorm

# Sample data
cities = ['City A', 'City B', 'City C', 'City D', 'City E',
          'City F', 'City G', 'City H', 'City I', 'City J']
genepy_rank = [3, 1, 4, 2, 5, 8, 7, 10, 9, 6]
fitness_rank = [7, 9, 2, 5, 4, 6, 3, 1, 8, 10]

# Calculate the difference in ranking
diff_rank = [genepy - fitness for genepy, fitness in zip(genepy_rank, fitness_rank)]
dmin, dmax = min(diff_rank), max(diff_rank)

boundaries = [dmin-0.5]+[d+0.5 for d in range(dmin, dmax+1)]
cm = plt.get_cmap('Spectral')
norm = BoundaryNorm(boundaries, 256)

print(type(norm))
# Plot the graph
fig, ax = plt.subplots(layout='constrained')
for i, city in enumerate(cities):
    x = [genepy_rank[i], fitness_rank[i]]
    y = [i, i]
    color = cm(norm(diff_rank[i]))
    ax.plot(x, y,  color=color, marker='o')
    ax.annotate(city, (x[0], y[0]), xytext=(-20, 20),
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
ax.set_xlim(0, 11)
ax.set_ylim(-1, 11)
cb = plt.colorbar(ScalarMappable(norm, cm), ax=ax)
cb.set_ticks(range(dmin, dmax+1))
cb.set_ticklabels(['%+2d'%t for t in range(dmin, dmax+1)])
cb.setlabel('Ranking Difference (genepy -fitness)')
plt.show()

我不得不说,我不认为这是一个很好的方式来显示您的数据(即使它可能是最好的一个,我不知道...)。

相关问题