首页 > 解决方案 > pyplot:绘制具有多个 Y 值和分类 X 值的散点图

问题描述

我正在尝试使用从实验中收集的指标数据创建一个简单的散点图。每天,我测试多个实验样本,样本数量各不相同。我正在尝试创建一个散点图,其中将天数作为 x 值,并将当天收集的所有实验值作为 y 值。

到目前为止,我已经尝试了几种方法。

我将省略完整的代码,但这里是数据的示例:

XVals = ['10-Dec-18', '11-Dec-18']
YVals = [[0.88, 0.78, 0.92, 0.98, 0.91],[0.88, 0.78, 0.92, 0.98]]

由于 pyplot 希望 x 和 y 具有相同的维度,我尝试了以下建议

for xe, ye in zip(XVals, YVals):
   plt.scatter([xe] * len(ye), ye)

这给了我一个值错误,因为我的 xval 是字符串。

ValueError: could not convert string to float: '10-Dec-18'

我也尝试以下列方式生成绘图,但我再次收到一条错误消息,因为 x 和 y 的维度不同:

fig, ax = plt.subplots()
ax.scatter(XVals, YVals)
plt.show()

这给了我明显的错误:

ValueError: x and y must be the same size

我还没有找到任何类似情节的例子(多个 Y 值和分类 X 值)。任何帮助,将不胜感激!

标签: pythonmatplotlibscatter-plot

解决方案


One option is to create flattened lists for the data. The first list, X, will contain the day of each data point. Each day is repeated n times, where n is the number of data points for that day. The second list Y is simply a flattened version of YVals.

import matplotlib.pyplot as plt

XVals = ['10-Dec-18', '11-Dec-18']
YVals = [[0.88, 0.78, 0.92, 0.98, 0.91],[0.88, 0.78, 0.92, 0.98]]

X = [XVals[i] for i, data in enumerate(YVals) for j in range(len(data))]
Y = [val for data in YVals for val in data]

plt.scatter(X, Y)
plt.show()

enter image description here


推荐阅读