ggplot python:如何在表示每个点的线图中插入“计数”

时间:2018-01-23 22:03:13

标签: python pandas matplotlib python-ggplot

我试图想象多年来每个类别的计数。我的数据框如下:

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

enter image description here

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

2 个答案:

答案 0 :(得分:0)

试试这个:

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)

结果:

enter image description here

数据:

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

答案 1 :(得分:0)

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

enter image description here