python - 如何绘制范围数据的散点图
问题描述
我有范围数据,例如,一家教育机构正在向一批学生收取在线课程的费用。
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 的数据转换为 xlable。
解决方案
和数组可以转换为可用于创建散点图的数值数组x
:y
- 将 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]]
- 在对应的 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])]
- 重新组合 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]]]
- 展平 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, ...]
- 创建散点图
plt.xticks(x_result)
plt.ylim(0, max(y_result)+1000)
plt.scatter(x_result, y_result)
plt.show()
推荐阅读
- java - 单选按钮组获取表的值
- python - 为什么我不能在 wxPython 中绘制两个不同的位图?
- javascript - 带有 Webpack 5 的影子 DOM 中的 CSS
- react-native - 使用本机反应创建计时器
- ethereum - 以太坊合约可以直接在比特币上执行交易吗?
- algorithm - 这是分类问题还是回归问题?什么算法可以用来解决它?
- android - 如何将从 firebase 检索到的数据保存到 arraylist
- python - 熊猫总和然后除以唯一计数
- jupyter-notebook - 将 nbextensions 与 Jupyter Server 一起使用的正确方法是什么(WinPython 3.8.8)
- java - 将对象列表转换为地图
使用地图/流/收集