[英]How to create a scatter plot with yticklabels in a custom order
我可以這樣做並產生分散嗎?
y-axis tick/label order → [0, 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]
x = ('a', 'b', 'c', 'd', 'e')
y = [[1,5,2], [10,5,11,7], [9], [], [ 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5]]
這個想法是將 x 值映射到 y 值。 例如,數據列表中的第一個( 'a'
)是,例如,擊中目標 1、5 和 2,第二個( 'b'
)擊中分數 10、5、11、7。我需要保留 Y -axis 按所示順序作為標簽。
該實現包括按照ticklabels
定義的順序獲取 y 軸ticklabels
yticks
,這需要將yticklabels
更改為與默認 ytick 坐標不匹配的內容。
import matplotlib.pyplot as plt
x_labels = ("a", "b", "c", "d", "e")
yticks = (0, 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5)
# y values to be plotted
y_lists = ([1, 5 , 2], [10, 5, 11, 7], [9], [], [7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5])
# Define the figure and ax.
fig, ax = plt.subplots(figsize=(8, 5))
for x, y_list in zip(x_labels, y_lists):
# We have a single x value for each letter, but we need the x-list to be as long y-list in order to make a scatter.
x_list = [x]*len(y_list)
# Notice the use of `.index` here to accommodate the ticks not being ordered.
true_y_list = [yticks.index(y) for y in y_list]
ax.scatter(x_list, true_y_list)
# set the sorted y-ticks.
ax.set_yticks(sorted(yticks))
ax.set_yticklabels(yticks)
# set the x-ticks because the API will not show D on the axis since it has no y values
ax.set_xticks(range(len(x_labels)))
ax.set_xticklabels(x_labels) # `ax.set_xticklabels("abcde")` would work too.
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.