垂直线到散点图中的点 [英] Vertical lines to points in scatter plot

查看:42
本文介绍了垂直线到散点图中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组点x和一组对应的数据y.我现在将这些绘制在散点图中,plt.scatter(x,y).我得到的数字包含一些由 matplotlib 生成的 x 轴刻度.有没有办法实现自动滴答,但要从 x 轴添加垂直线到散点图中的点并标记它们?

Suppose I have a set of points x and a set of corresponding data y. I now plot these in a scatter plot, plt.scatter(x,y). The figure I get contains some x axis tick generated by matplotlib. Is there a way I can attain the automatic ticking, but to add vertical lines from the x-axis to the point in the scatter and label them?

推荐答案

喜欢吗?

如果是,那么这里是必需品.

If so then here are the essentials.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import collections as matcoll

x = np.arange(1,13)
y = [15,14,15,18,21,25,27,26,24,20,18,16]

lines = []
for i in range(len(x)):
    pair=[(x[i],0), (x[i], y[i])]
    lines.append(pair)

linecoll = matcoll.LineCollection(lines)
fig, ax = plt.subplots()
ax.add_collection(linecoll)

plt.scatter(x,y)

plt.xticks(x)
plt.ylim(0,30)

plt.show()

附录:

对于彩色圆点,将 plt.scatter(x,y)替换为:

For coloured dot, replace plt.scatter(x,y) with:

colours = ['Crimson', 'Blue', 'Fuchsia', 'Gold', 'Green', 'Tomato', 'Indigo', 'Turquoise', 'Brown', 'Wheat', 'Yellow',]
plt.scatter(x,y,c=colours)

  • 有关指定颜色的可选方式,请参阅指定颜色.
  • 有关X11颜色名称及其对应的十六进制代码的列表,请参见 X11颜色.
  • .立>
  • 请注意,matplotlib似乎不喜欢两个单词的颜色名称,例如'Hot Pink'.
  • 附录 2:

    根据要求,最简单的方法可能是使用第二个答案中提供的建议,并进行适当调整.

    The easiest way, depending on requirements, might be to use the suggestion offered in the second answer, suitably adapted.

    import matplotlib.pyplot as plt
    from datetime import datetime
    from random import randint
    
    x = [datetime(2019, 6, i) for i in range(1,21)]
    y = [randint(10,20) for i in range(1,21)]
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    plt.xticks(rotation=90) 
    ax.stem(x, y, markerfmt=' ')
    plt.show()
    

    这篇关于垂直线到散点图中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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