簡體   English   中英

如何以自定義順序創建帶有 yticklabels 的散點圖

[英]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 按所示順序作為標簽。

樣本2

該實現包括按照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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM