Python散点图,每个X有多个Y值

2024-04-24 07:20:48 发布

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

我试图使用Python创建一个散点图,其中包含两个X类别“cat1”“cat2”,每个类别有多个Y值。如果每个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()

但只要每个X值的Y值的数目不相同,我就会得到一个错误。例如,这不起作用:

    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

如何为每个X值绘制不同数量的Y值,如何将X轴从数字1和2更改为文本类别“cat1”和“cat2”。我非常感谢你的帮助!

以下是我正在尝试绘制的绘图类型的示例图像:

http://s12.postimg.org/fa417oqt9/pic.png


Tags: importnumpyforplotmatplotlibasshownp
1条回答
网友
1楼 · 发布于 2024-04-24 07:20:48

How can I plot different numbers of Y values for each X value

只需分别绘制每组:

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".

手动设置刻度和刻度标签:

plt.xticks([1, 2])
plt.axes().set_xticklabels(['cat1', 'cat2'])

完整代码:

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')

enter image description here

相关问题 更多 >