【问题标题】:Change line width of specific line in line plot pandas/matplotlib更改线图 pandas/matplotlib 中特定线的线宽
【发布时间】:2020-10-09 17:39:57
【问题描述】:

我正在绘制一个看起来像这样的数据框。

Date    2011    2012    2013    2014    2015    2016    2017    2018    2019    2020
Date                                        
01 Jan  12.896  13.353  12.959  13.011  13.073  12.721  12.643  12.484  12.876  13.102
02 Jan  12.915  13.421  12.961  13.103  13.125  12.806  12.644  12.600  12.956  13.075
03 Jan  12.926  13.379  13.012  13.116  13.112  12.790  12.713  12.634  12.959  13.176
04 Jan  13.051  13.414  13.045  13.219  13.051  12.829  12.954  12.724  13.047  13.187
05 Jan  13.176  13.417  13.065  13.148  13.115  12.874  12.956  12.834  13.098  13.123

绘图代码在这里。

ice_data_dates.plot(figsize=(20,12), title='Arctic Sea Ice Extent', lw=3, fontsize=16, ax=ax, grid=True)

这会为数据框中列出的每一年绘制一年中每一天的线图。但是,我想让 2020 年的线条比其他线条更粗,以便更清晰地突出。有没有办法使用这一行代码来做到这一点?或者我是否需要手动绘制所有年份以便我可以分别控制每条线的粗细?附上一张现在的图片,线条粗细都是一样的。

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案1】:

    你可以像这样分两行来做:

    ice_data_dates.loc[:, ice_data_dates.columns != "2020"].plot(figsize=(20, 12), title='Arctic Sea Ice Extent', lw=3, fontsize=16, ax=ax, grid=True)
    ice_data_dates["2020"].plot(figsize=(20, 12), title='Arctic Sea Ice Extent', lw=15, fontsize=16, ax=ax, grid=True)
    

    这将首先绘制除 2020 列之外的整个 DataFrame,然后仅绘制 2020。输出如下所示:

    这使用不同的方法作为选择的答案,但它给出了相同的结果。

    【讨论】:

      【解决方案2】:

      您可以遍历绘图中的线条,可以使用ax.get_lines 检索,如果其label 与感兴趣的值匹配,则使用set_linewidth 增加宽度:

      fig, ax = plt.subplots()
      df.plot(figsize=(20,12), title='Arctic Sea Ice Extent', 
              lw=3, fontsize=16, ax=ax, grid=True)
      
      for line in ax.get_lines():
          if line.get_label() == '2020':
              line.set_linewidth(15)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-27
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        • 2016-05-16
        相关资源
        最近更新 更多