CGHA
CGHA

Reputation: 37

Three subplots in Python using the same data

I'm currently needing some help here since I’m kinda novice. So I was able to import and plot my time series data via Pandas and Matplotlib, respectively. The thing is, the plot is too cramped up (due to the amount of data lol).

Using the same data set, is it possible to ‘divide’ the whole plot into 3 separate subplots?

Here's a sample to what I mean:
enter image description here

What I'm trying to do here is to distribute my plot into 3 subplots (it seems it doesn't have ncol=x).

Initially, my code runs like this;

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

pd.options.display.float_format = '{:,.4f}'.format
data = pd.read_csv ('all_visuallc.csv')   
df = pd.DataFrame(data, columns= ['JD', 'Magnitude'])
print(df) #displays ~37000ish data x 2 columns

colors = ('#696969') #a very nice dim grey heh
area = np.pi*1.7

ax = df.plot.scatter(x="JD", y="Magnitude", s=area, c=colors, alpha=0.2)
ax.set(title='HD 39801', xlabel='Julian Date', ylabel='Visual Magnitude')
ax.invert_yaxis()
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())

plt.rcParams['figure.figsize'] = [20, 4]
plt.rcParams['figure.dpi'] = 250
plt.savefig('test_p.jpg')
plt.show()

which shows a very tight plot:

enter image description here

Thanks everyone and I do hope for your help and responses.

P.S. I think iloc[value:value] to slice from a df may work?

Upvotes: 1

Views: 143

Answers (1)

Elya Fadeeva
Elya Fadeeva

Reputation: 168

First of all, you have to create multiple plots for every part of your data. For example, if we want to split data into 3 parts, we will create 3 subplots. And then, as you correctly wrote, we can apply iloc (or another type of indexing) to the data.

Here is a toy example, but I hope you are be able to apply your decorations to it.

y = np.arange(0,20,1)
x = np.arange(20,40,1)
sample = pd.DataFrame(x,y).reset_index().rename(columns={'index':'y', 
0:'x'})

n_plots = 3
figs, axs = plt.subplots(n_plots, figsize=[30,10])
# Suppose we want to split data into equal parts
start_ind = 0
for i in range(n_plots):
    end_ind = start_ind + round(len(sample)/n_plots) #(*)
    part_of_frame = sample.iloc[start_ind:end_ind]
    axs[i].scatter(part_of_frame['x'], part_of_frame['y'])
    start_ind = end_ind

Sample

It's also possible to split data into unequal parts by changing the logic in the string (*)

Upvotes: 1

Related Questions