- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to plot two Pandas time series on the same plot with legends and secondary Y-axis in Matplotlib?
To plot two Pandas time series on the sameplot with legends and secondary Y-axis, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a one-dimensional ndarray with axis labels (including time series).
Make a dataframe with some column list.
Plot columns A and B using dataframe plot() method.
Return the handles and labels for the legend using get_legend_handles_labels() method.
Place a legend on the figure using legend() method.
To display the figure, use show() method.
import pandas as pd from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True ts = pd.Series(np.random.randn(10), index=pd.date_range('2021-04-10', periods=10)) df = pd.DataFrame(np.random.randn(10, 4), index=ts.index, columns=list('ABCD')) ax1 = df.A.plot(color='red', label='Count') ax2 = df.B.plot(color='yellow', secondary_y=True, label='Sum') h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() plt.legend(h1+h2, l1+l2, loc=2) plt.show()
- How to plot on secondary Y-Axis with Python Plotly?
- How can I plot two different spaced time series on one same plot in Python Matplotlib?
- Plot two horizontal bar charts sharing the same Y-axis in Python Matplotlib
- How to plot multiple Pandas columns on the Y-axis of a line graph (Matplotlib)?
- Plot multiple time-series DataFrames into a single plot using Pandas (Matplotlib)
- How to plot two violin plot series on the same graph using Seaborn?
- How do you plot a vertical line on a time series plot in Pandas?
- How to plot multiple histograms on same plot with Seaborn using Matplotlib?
- How to plot data from multiple two-column text files with legends in Matplotlib?
- How to plot multiple lines on the same Y-axis in Python Plotly?
- Annotate Time Series plot in Matplotlib
- How to plot arbitrary markers on a Pandas data series using Matplotlib?
- Plot a histogram with Y-axis as percentage in Matplotlib
- How to get all the legends from a plot in Matplotlib?
- Show the origin axis (x,y) in Matplotlib plot