Plot different DataFrames in the same figure
Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby
and unstack
ing:
(Assuming you have this in dataframe, with datetime index already)
In [1]: df
Out[1]:
value
datetime
2010-01-01 1
2010-02-01 1
2009-01-01 1
# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)
In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
value
Year 2009 2010
Month
1 1 1
2 NaN 1
Now it's easy to plot (each year as a separate line):
df.groupby(['Month','Year']).mean().unstack().plot()
plotting two different dataframes on the same plot
You just need to store the ax
handle from the first plot and pass it as ax
argument to the second plot:
plt_ax = ts_rec.plot(
x=x, subplots=True, layout=(7, 4), lw=2, legend=False,
figsize=(12, 10), sharey=True, color='green')
ts_exp.plot(
ax=plt_ax, x=x, subplots=True, layout=(7, 4), lw=2, legend=False,
figsize=(12, 10), sharey=True, color='red')
Pandas plot three dataframes on the same figure
I solved simply by putting an array of colors... it's not specified anywhere but when you concatenate you can keep the original colors by adding an array like color=['r', 'g', 'b']).
Here is the modification I used, in case anyone would know:
concat = pd.concat(merged_data_frames, axis=0, sort=True)
concat = concat.sort_index(key=lambda x: x.str.split().str[1].str.zfill(5))
concat.plot(kind='bar', y='total_mean', use_index=True, yerr='error_mean', edgecolor='black', color=['r', 'g', 'b'])
Plot multiple plots on same figure using loops in pandas
You can try this:
for i in range(2,5):
plt.plot(df["Time"], df[f"Amount i={i}"]
# and do not forget
plt.show()
How can I plot multiple dataframes on the same figure from an excel sheet using pandas?
SolutionLet us assume that you have three dataframes: df0
, df1
and df2
. Additionally, let us assume that in each dataframe you have two columns: x
and y
. If we make a list of these dataframes, dfs = [df0, df1, df2]
, then you could plot all three of them on the same plot as follows.
The solution here is divided into two sections:
- Makinng dummy data (this is only needed for reproducing some dummy data).
- Plotting the dataframes (you will need to use this code).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg' # 'svg', 'retina'
plt.style.use('seaborn-white')
# Make Dummy Data
N = [100, 125, 150]
P = [[3, 2.2], [5, 3.7], [2, 4]]
dfs = list()
for n, p in zip(N, P):
x = np.arange(n)
y = p[0]*x**p[1] + np.average(p)
df = pd.DataFrame({'x': x, 'y': y})
dfs.append(df.copy())
# Make Plots
#dfs = [df1, df2, df3]
for i,df in enumerate(dfs):
plt.plot(df['x'], df['y'],
linestyle='--',
alpha=0.8,
label='df{}'.format(i))
plt.legend(loc='best')
plt.show()
Output:
Related Topics
Filter Df When Values Matches Part of a String in Pyspark
Quickest Way to Find the Nth Largest Value in a Numpy Matrix
How to Extract List from List of Lists When Any One Element Match With Another List'S Element
Counting Number of Zeros Per Row by Pandas Dataframe
Checking If Particular Value (In Cell) Is Nan in Pandas Dataframe Not Working Using Ix or Iloc
Python, Pandas:Write Content of Dataframe into Text File
Convert Commas Decimal Separators to Dots Within a Dataframe
Filter All Rows That Do Not Contain Letters (Alpha) in 'Pandas'
Python - Regex Match Multiple Patterns in Multiple Lines
Python: How to Turn CSV Data in to Array
How to Find and Replace a Part of a Value in Json File
How to Align Labels and Entry Boxes in a Gui Program
How to Add a Path to Pythonpath in Virtualenv
How to Substitute Value for a Variable in a Json in Python
Changing Only One Row to Column in Python