我可以使用下面的代码用两条线绘制一个图。
# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Data
df=pd.DataFrame({'dates': ['2001','2002','2003','2030'], 'census_people': [306,327,352,478], 'census_houses': [150,200,249,263]})
# multiple line plot
plt.plot('dates', 'census_people', data=df, marker='o', color='green', linewidth=2)
plt.plot('dates','census_houses',data=df,marker='o',color='orange',linewidth=2)
我的问题是,我希望两条线都牢固,除了2003年至2030年之间的那部分线,我想用虚线表示(因为这是对未来情况的预测)。像this这样,过去的数据(即连接前三个数据点的线)是实线,而未来的投影数据(即连接第三和第四数据点的线)是虚线
(我可以找到很多绘制虚线的示例,只是没有在同一条线上绘制实线和虚线)。
答案 0 :(得分:1)
我不知道您是否有办法做到这一点,但我要做的是分别绘制它们:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Data
df=pd.DataFrame({'dates': [2001, 2002, 2003, 2030], 'census_people': [306,327,352,478], 'census_houses': [150,200,249,263]}) #I changed the dates from strings to ints
# multiple line plot
plt.plot('dates', 'census_people', data=df[df['dates'] < 2004], marker='o', color='green', linewidth=2)
plt.plot('dates', 'census_people', data=df[df['dates'] > 2002], marker='o', color='green', linewidth=2, linestyle = '--')
plt.plot('dates','census_houses',data=df[df['dates'] < 2004] ,marker='o',color='orange', linewidth=2)
plt.plot('dates','census_houses',data=df[df['dates'] > 2002] ,marker='o',color='orange', linewidth=2, linestyle = '--')