Python散点图,每个X具有多个Y值 [英] Python Scatter Plot with Multiple Y values for each X

查看:2114
本文介绍了Python散点图,每个X具有多个Y值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python创建一个散点图,该散点图包含两个X类别"cat1"和"cat2",每个类别具有多个Y值.如果使用以下代码,则每个X值的Y值数目相同时,我可以使它工作:

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:

    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值数量不同时,就会出现错误.例如,这不起作用:

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:

    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".我将不胜感激,对此有任何帮助!

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!

这是我要制作的情节类型的示例图像:

Here is a sample image of the type of plot I am trying to make:

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

推荐答案

如何为每个X值绘制不同数量的Y值

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)

以及如何将X轴从数字1和2更改为文本类别"cat1"和"cat2".

and how can I change the X axis from being the numbers 1 and 2 to text categories "cat1" and "cat2".

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

Set ticks and tick labels manually:

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

这篇关于Python散点图,每个X具有多个Y值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆