![](/img/trans.png)
[英]How to change color of data points on a scatter plot according to an age range?
[英]How to plot scatter plot for range data
我有范圍數據,例如,一家教育機構正在向一批學生收取在線課程的費用。
1-4名學生報名費用為10000/批
5-10名學生報名費用為15000/批
11-20人報名費用為22000/批
x = ['1-4','5-10','11-20']
y = [10000,15000,20000]
x 和 y 是 matplotlib 的 xlable 和 ylable。 在這種情況下如何將 x 和 plot 的數據轉換為 xlable。
x
和y
arrays 可以轉換為可用於創建散點 plot 的數值的 arrays:
x_ranges = [list(range(int(xi[0]), int(xi[1])+1)) for xi in [xi.split('-') for xi in x]]
#[[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]
y_expanded = [(x[0], [x[1]]*len(x[0])) for x in zip(x_ranges,y)]
#[([1, 2, 3, 4], [10000, 10000, 10000, 10000]),
# ([5, 6, 7, 8, 9, 10], [15000, 15000, 15000, 15000, 15000, 15000]),
# ([11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
# [20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000])]
xy_sorted = list(map(list, zip(*y_expanded)))
#[[[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]],
# [[10000, 10000, 10000, 10000],
# [15000, 15000, 15000, 15000, 15000, 15000],
# [20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000]]]
x_result = [x for sublist in xy_sorted[0] for x in sublist]
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
y_result = [y for sublist in xy_sorted[1] for y in sublist]
#[10000, 10000, 10000, 10000, 15000, 15000, ...]
plt.xticks(x_result)
plt.ylim(0, max(y_result)+1000)
plt.scatter(x_result, y_result)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.