如何绘制范围数据的散点图

2024-06-16 12:32:45 发布

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

我有范围数据,例如,一家教育机构正在为一批在线课程的学生收费

If 1-4 students join the fee is 10000/per batch

If 5-10 students join the fee is 15000/per batch

If 11-20 students join the fee is 22000/per batch

x = ['1-4','5-10','11-20']
y = [10000,15000,20000]

x和y是matplotlib的xlable和Yable。在这种情况下,如何转换x的数据并将其打印为xlable


Tags: the数据if机构matplotlibisbatch学生
1条回答
网友
1楼 · 发布于 2024-06-16 12:32:45

可以将xy数组转换为数值数组,用于创建散点图:

  1. 将x字符串转换为范围
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]]
  1. 在相应的x范围内,每个条目添加一个y元素
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])]
  1. 将x和y阵列重新分组
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]]]
  1. 展平x和y值的列表
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, ...]
  1. 创建散点图
plt.xticks(x_result)
plt.ylim(0, max(y_result)+1000)
plt.scatter(x_result, y_result)
plt.show()

scatterplot

相关问题 更多 >