在matplotlib时间序列“意大利面”图中使线变粗

时间:2019-01-08 18:54:56

标签: python pandas matplotlib

感谢您的阅读。

我有一个图,想让我的数据集中的最新年份脱颖而出。我的数据只是一个长期序​​列,所以我想绘制同比比较,因此先进行透视,然后绘制。

第一段代码运行并大致给出我所追求的目标(没有最新年份脱颖而出),然后在第二段代码中,我尝试使我的最新版本脱颖而出(在技术上可行),但是颜色是不同,与图例不符,甚至可以与另一年相同。

我可以在背景中看到旧系列。我想我正在创建另一个图并将其放在顶部,但是如何才能选择最近一年的原始线条(在这种情况下为2018年)并使其突出呢?

还是有更好的方法来完成整个过程? 任何有关代码,格式或其他方面的技巧都将不胜感激,我对此很陌生!

非常感谢!

13sen1


第一块

# import
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# create fake time series dataframe
index = pd.date_range(start='01-Jan-2012', end='01-01-2019', freq='M')
data = np.random.randn(len(index))
df = pd.DataFrame(data, index, columns=['Data'])

# pivot to get by month in rows, then year in columns
df_pivot = pd.pivot_table(df, index=df.index.month, columns=df.index.year, values='Data')

# plot
df_pivot.plot(title='Data by Year', figsize=(6,4))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.tight_layout()
plt.show()

firstblockresult

第二个块

# import
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# create fake time series dataframe
index = pd.date_range(start='01-Jan-2012', end='01-01-2019', freq='M')
data = np.random.randn(len(index))
df = pd.DataFrame(data, index, columns=['Data'])

# pivot to get by month in rows, then year in columns
df_pivot = pd.pivot_table(df, index=df.index.month, columns=df.index.year, values='Data')

# plot
df_pivot.plot(title='Data by Year', figsize=(6,4))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.tight_layout()

# plot the thicker last line
# **************** ERROR HERE *************************
plt.plot(df_pivot.iloc[:, -1:], lw=4, ls='--')
# **************** ERROR HERE *************************
plt.show()

secondblockresult

1 个答案:

答案 0 :(得分:2)

您可以使上一年的行更粗。因为列已排序,所以它将是轴上的最后一行(索引-1)。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# create fake time series dataframe
index = pd.date_range(start='01-Jan-2012', end='01-01-2019', freq='M')
data = np.random.randn(len(index))
df = pd.DataFrame(data, index, columns=['Data'])

# pivot to get by month in rows, then year in columns
df_pivot = pd.pivot_table(df, index=df.index.month, columns=df.index.year, values='Data')

# plot
ax = df_pivot.plot(title='Data by Year', figsize=(6,4))
ax.get_lines()[-1].set_linewidth(5)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

ax.figure.tight_layout()
plt.show()

enter image description here