简体   繁体   中英

How to plot multiple data one after another in the same graph using Python Pandas DataFrame

I was trying to visualize a facebook stock dataset, where the data for 2014 to 2018 is stored. The dataset looks like this: dataset screenshot

My goal is to visualize the closing column, but by year. That is, year 2014, then 2015 and so on, but they should be in one figure, and one after another. Something like this: expected graph image

But whatever I try, all the graph parts start from index 0, instead of continuing from the end of the previous one. Here's what I got: the graph I generated

Please help me to solve this problem. Thanks!

The most straightforward way is simply to create separate dataframes with empty values for the non-needed dates.

Here I use an example dataset.

import pandas as pd
import numpy as np

df = pd.DataFrame(
    np.random.randint(0, 100, size=100),
    index=pd.date_range(start="2020-01-01", periods=100, freq="D"),
)

Then you can create and select the data to plot

df1 = df.copy()
df2 = df.copy()

df1[df.index > pd.to_datetime('2020-02-01')] = np.NaN
df2[df.index < pd.to_datetime('2020-02-01')] = np.NaN

And then simply plot these on the same axis.

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(18, 8))

ax.plot(df1)
ax.plot(df2)

The result

在此处输入图像描述

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