【问题标题】:How to show line chart for the given data with legends and labels?如何使用图例和标签显示给定数据的折线图?
【发布时间】:2017-03-07 11:14:03
【问题描述】:

数据:

Taluka_name     Year_2010   Year_2011   Year_2012   Year_2013
AKOLA            7323.9        7665.9      3462     2384.4
AKOT             5471.3        5583.3      972.5    1253.2
BALAPUR          4571.8        4915.6      1961.2   1637.1
BARSHI_TAKALI    4077.4        4203.7      2225.5   1017
MURTIJAPUR       3258.5        3326.5      1463.5   908.5
PATUR            3444.8        3526.3      2340.3   1063.5
TELHARA          4199.1        4287.4      2156.9   1699.4

我想画一个折线图。 其中年份在 x 轴中,y 轴将是 Taluka_name。

x 轴标签显示“2010 年、2011 年、2012 年、2013 年”而不是 1 ,2 ,3 ,4

在 y 轴上的标签显示“AKOLA”、“AKOT”、“BALAPUR”……等等。

并且对于每个 taluka_name ,线条颜色都会改变。

我正在使用 matplotlib。

我试过这段代码:但我没有在折线图中得到标签名称和不同的颜色。

代码:

>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> data = pd.read_csv('/home/desktop/gram.csv')
>>> data2=data[['Year_2010','Year_2011','Year_2012','Year_2013']]
>>> data1=data['Taluka_name']
>>> fig, ax = plt.subplots()
>>> ax.plot( data2, 'k--', label='Year')
[<matplotlib.lines.Line2D object at 0x7f42a35b5f90>, <matplotlib.lines.Line2D object at 0x7f42a34ecd90>, <matplotlib.lines.Line2D object at 0x7f42a34eced0>, <matplotlib.lines.Line2D object at 0x7f42a34f9050>, <matplotlib.lines.Line2D object at 0x7f42a34f9190>, <matplotlib.lines.Line2D object at 0x7f42a34f92d0>]
>>> legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')
>>> legend.get_frame().set_facecolor('#00FFCC')
>>> plt.show()
>>> 

【问题讨论】:

    标签: python matplotlib linechart


    【解决方案1】:

    只需使用 pandas 绘图功能:

    In [14]: df
    Out[14]: 
         Taluka_name  Year_2010  Year_2011  Year_2012  Year_2013
    0          AKOLA     7323.9     7665.9     3462.0     2384.4
    1           AKOT     5471.3     5583.3      972.5     1253.2
    2        BALAPUR     4571.8     4915.6     1961.2     1637.1
    3  BARSHI_TAKALI     4077.4     4203.7     2225.5     1017.0
    4     MURTIJAPUR     3258.5     3326.5     1463.5      908.5
    5          PATUR     3444.8     3526.3     2340.3     1063.5
    6        TELHARA     4199.1     4287.4     2156.9     1699.4
    
    In [15]: df=df.set_index('Taluka_name')
    
    In [16]: df.transpose().plot()
    

    您确定要将 y 轴标签设为 Taluka 名称吗?那你怎么打印一行呢?

    【讨论】:

    • ,谢谢你能给我一些关于线条图案的想法,给出不同的风格,比如 AKOLA 它将是(--),对于 AKOT 它将是(:::)?
    • @Seabastian ,哦,是的,你是对的,不需要将 y 轴作为 taluka 名称
    • 你说的是x轴。根据此将style= 提供给绘图方法:matplotlib.org/examples/lines_bars_and_markers/…
    • @Seabastian,正确。谢谢,它会告诉我等待 3 分钟以接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多