[英]Python Scatter Plot with Multiple Y values for each X
I am trying to use Python to create a scatter plot that contains two X categories "cat1" "cat2" and each category has multiple Y values.我正在尝试使用 Python 创建一个散点图,其中包含两个 X 类别“cat1”“cat2”,并且每个类别都有多个 Y 值。 I can get this to work if the number of Y values for each X value is the same by using this following code:
如果每个 X 值的 Y 值数量相同,我可以使用以下代码使其工作:
import numpy as np
import matplotlib.pyplot as plt
y = [(1,1,2,3),(1,1,2,4)]
x = [1,2]
py.plot(x,y)
plot.show()
but as soon as the number of Y values for each X value is not the same, I get an error.但是一旦每个 X 值的 Y 值数量不同,我就会收到错误消息。 For example this does not work:
例如,这不起作用:
import numpy as np
import matplotlib.pyplot as plt
y = [(1,1,2,3,9),(1,1,2,4)]
x = [1,2]
plt.plot(x,y)
plot.show()
#note now there are five values for x=1 and only four for x=2. error
How can I plot different numbers of Y values for each X value and how can I change the X axis from being the numbers 1 and 2 to text categories "cat1" and "cat2".如何为每个 X 值绘制不同数量的 Y 值,以及如何将 X 轴从数字 1 和 2 更改为文本类别“cat1”和“cat2”。 I would greatly appreciate any help on this!
我将不胜感激对此的任何帮助!
Here is a sample image of the type of plot I am trying to make:这是我正在尝试制作的绘图类型的示例图像:
http://s12.postimg.org/fa417oqt9/pic.png http://s12.postimg.org/fa417oqt9/pic.png
How can I plot different numbers of Y values for each X value
如何为每个 X 值绘制不同数量的 Y 值
Just plot each group separately:只需分别绘制每个组:
for xe, ye in zip(x, y):
plt.scatter([xe] * len(ye), ye)
and how can I change the X axis from being the numbers 1 and 2 to text categories "cat1" and "cat2".
以及如何将 X 轴从数字 1 和 2 更改为文本类别“cat1”和“cat2”。
Set ticks and tick labels manually:手动设置刻度和刻度标签:
plt.xticks([1, 2])
plt.axes().set_xticklabels(['cat1', 'cat2'])
Full code:完整代码:
import matplotlib.pyplot as plt
import numpy as np
y = [(1,1,2,3,9),(1,1,2,4)]
x = [1,2]
for xe, ye in zip(x, y):
plt.scatter([xe] * len(ye), ye)
plt.xticks([1, 2])
plt.axes().set_xticklabels(['cat1', 'cat2'])
plt.savefig('t.png')
To respond to the comment from javadba, I was able to plot multiple dependent variables (new covid cases) for a single independent variable (date) using matplotlib.为了回应 javadba 的评论,我能够使用 matplotlib 为单个自变量(日期)绘制多个因变量(新的 covid 案例)。
plt.xticks(rotation=90)
plt.scatter(x=dates_uk[::5], y=cases_uk[::5])
plt.scatter(x=dates_us[::5], y=cases_us[::5])
classes = ['UK New Cases', 'US New Cases']
plt.legend(labels=classes)
plt.show()
Image of what the code shows (not enough reputation to show image)代码显示的图像(没有足够的声誉来显示图像)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.