简体   繁体   中英

Python - Plot time series data and connect two points using line

While it seems not that difficult, for the life of me, I'm unable to figure this out. Any help will be greatly appreciated. Here is my scenario:

I have a dataframe, df1, that contains Date and Price. I can use this data to plot a graph using matplotlib.pyplot. Good so far.

I have another dataframe, df2, that contains again Date and Price information but only 6 rows. Now, I need to take the first two rows of df2and consider them as two points (x axis would be Date and y axis would be Price) and and connect them on the graph plotted above. Same with next two rows and so on. (there will be more rows in df2, but I hope you get the drift).

I tried calling plot() on both dfs one after the other - the result is that when df2.plot() is called, the graph plotted using df1.plot() is erased and df2 lines are plotted.

Below is how I need the result to look like. 在此处输入图片说明

df = pd.read_csv(r'https://vincentarelbundock.github.io/Rdatasets/csv/fpp2/goog200.csv', index_col=0)
df2 = df.loc[[57, 98, 169]]

plt.plot(df['time'], df['value'])
plt.plot(df2['time'], df2['value'])
plt.show()

在此处输入图片说明


Edit per comment

(Credit to user23564's linked answer in the comments to the OP)

df = pd.read_csv(r'https://vincentarelbundock.github.io/Rdatasets/csv/fpp2/goog200.csv', index_col=0)
df2 = df.loc[[57, 98, 169, 200]].reset_index()

plt.plot(df['time'], df['value'])
for i in range(0, len(df2), 2):
    plt.plot(df2.loc[i:i+1, 'time'], df2.loc[i:i+1, 'value'], c='grey')
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM