每个 X 具有多个 Y 值的 Python 散点图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34280444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:44:36  来源:igfitidea点击:

Python Scatter Plot with Multiple Y values for each X

pythonmatplotlibplot

提问by mangoplant

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. I can get this to work if the number of Y values for each X value is the same by using this following code:

我正在尝试使用 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()

but as soon as the number of Y values for each X value is not the same, I get an error. For example this does not work:

但是一旦每个 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

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". I would greatly appreciate any help on this!

如何为每个 X 值绘制不同数量的 Y 值,以及如何将 X 轴从数字 1 和 2 更改为文本类别“cat1”和“cat2”。我将不胜感激对此的任何帮助!

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

采纳答案by fjarri

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

enter image description here

在此处输入图片说明