【问题标题】:ggplot python: How to insert "counts" in line plots that represents each pointggplot python:如何在代表每个点的线图中插入“计数”
【发布时间】:2018-02-04 08:58:30
【问题描述】:

我正在尝试可视化每个类别在多年内的计数。我的数据框如下:

STATE    YEAR     COUNT
IN       2012        0
CA       2013       35
TX       2014       32

我用 ggplot 做了一个简单的折线图

ggplot(aes(x='YEAR', y='COUNT'), data=IN)  + geom_line() + geom_point(color = "red")+ ggtitle("RECORDS")

有没有办法在图表中的每个红点显示“计数”(0,35,32)?

【问题讨论】:

    标签: python pandas matplotlib python-ggplot


    【解决方案1】:

    试试这个:

    import matplotlib.pyplot as plt
    import matplotlib
    matplotlib.style.use('ggplot')
    
    ax = df.plot(x='YEAR',y='COUNT', c='black', lw=1.2)
    df.plot.scatter(x='YEAR',y='COUNT', c='r', s=30, ax=ax)
    df.apply(lambda x: ax.text(x['YEAR'], x['COUNT']+2, x['COUNT']), axis=1)
    

    结果:

    数据:

    In [200]: df
    Out[200]:
      STATE  YEAR  COUNT
    0    IN  2012      0
    1    CA  2013     35
    2    TX  2014     32
    3    IN  2015     37
    4    CA  2016     63
    5    TX  2017     81
    

    【讨论】:

    • 我现在确实看到了计数,但是点 '0' 和 '81' 在情节中被削减了一半。我尝试调整图像大小,但没有帮助
    • @sagar,我认为阻止它并同时使其通用...
    • 但是您的情节完美地显示了它。(您使用的示例)
    • @sagar,你的 Pandas 版本是什么?我正在使用熊猫 0.22.0
    • 当我尝试使用您的代码在数据框中绘制其他列时,出现以下错误。 ValueError: Image size of 418x142840 pixels is too large. It must be less than 2^16 in each direction.
    【解决方案2】:

    使用plotnine

    from io import StringIO
    import pandas as pd
    from plotnine import *
    
    sio = StringIO("""
      STATE  YEAR  COUNT
    0    IN  2012      0
    1    CA  2013     35
    2    TX  2014     32
    3    IN  2015     37
    4    CA  2016     63
    5    TX  2017     81
    """)
    
    df = pd.read_csv(sio, sep='\s+')
    
    (ggplot(aes(x='YEAR', y='COUNT'), data=df)
     + geom_line()
     + geom_point(color='red')
     + geom_text(aes(label='COUNT'), nudge_y=3, size=10)
     + labs(title='RECORDS')
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2018-12-22
      相关资源
      最近更新 更多