Putting two plots with different axes into one with Matplotlib - python

I have two plots in Matplotlib that I would like to merge. They have different axes and scales. Here is the code for each of them.
Electrical Power Plot:
#Case Study: Curtailment
from matplotlib import pyplot as plt
%matplotlib inline
load = [0, 250, 250, 250, 250, 250, 665, 2500, 2500, 2500, 2500, 2500,0,2500, 2366, 250, 250, 373, 2500,0, 2500, 0, 2500,250, 0]
hours = list(range(25)) # [0, 1, 2, ... 22, 23, 24]
labels = [f'{h:02d}:00' for h in hours] # ["00:00", "01:00", ... "23:00", "24:00"]
fig = plt.figure(linewidth=1, figsize=(9, 5))
ax = plt.gca()
ax.plot(hours, load, color="goldenrod",drawstyle="steps-post", linewidth=3) # <- drawstyle argument.
ax.set_xlabel("Time of day", fontsize=14, labelpad=8)
ax.set_ylabel("Electrical power in W", fontsize=14, labelpad=8)
ax.set_xlim(0, 24)
ax.set_ylim(0, 3000)
plt.xticks(hours, labels=labels, rotation=90)
plt.grid(axis='y', alpha=.4)
ax.tick_params(axis='both', which='major', labelsize=14)
# (Optional) ax.legend(loc='center left', bbox_to_anchor=(0.03, 1.15), fontsize = 14, ncol=3)
plt.tight_layout() # This must be called last, after all elements (plot and legend) are ready.
plt.savefig('CS_Curtailment_ElectricalLoad.png', edgecolor='black', dpi=400, bbox_inches='tight')
plt.show()
Temperature Plot:
#Case Study: Curtailment
from matplotlib import pyplot as plt
%matplotlib inline
temperature = [
21.00,
21.02,
20.96,
20.85,
20.68,
20.46,
20.40,
20.56,
20.77,
21.06,
21.41,
21.79,
21.10,
21.57,
22.00,
21.47,
20.92,
20.46,
20.92,
20.31,
20.77,
20.35,
20.90,
21.00,
21.00
]
hours = list(range(25)) # [0, 1, 2, ... 22, 23, 24]
labels = [f'{h:02d}:00' for h in hours] # ["00:00", "01:00", ... "23:00", "24:00"]
fig = plt.figure(linewidth=1, figsize=(9, 5))
ax = plt.gca()
ax.plot(hours, temperature, color="red", linewidth=3) # <- drawstyle argument.
ax.set_xlabel("Time of day", fontsize=14, labelpad=8)
ax.set_ylabel("Temperature in °C", fontsize=14, labelpad=8)
ax.set_xlim(0, 24)
ax.set_ylim(20, 22.5)
plt.xticks(hours, labels=labels, rotation=90)
plt.grid(axis='y', alpha=.4)
ax.tick_params(axis='both', which='major', labelsize=14)
# (Optional) ax.legend(loc='center left', bbox_to_anchor=(0.03, 1.15), fontsize = 14, ncol=3)
plt.tight_layout() # This must be called last, after all elements (plot and legend) are ready.
plt.savefig('CS_Curtailment_Temperature.png', edgecolor='black', dpi=400, bbox_inches='tight')
plt.show()
I would like to have the electrical power axis on the left (first plot) and the temperature axis on the right (second plot). Of course the two plots have similar x-axis values.
Can you do this with Matplotlib?
I'd appreciate every comment.

Yes this can be done in matplotlib to do so, first generate the first ax (electrical power) and then instantiate the second axes
ax.plot(hours, load, color="goldenrod",drawstyle="steps-post", linewidth=3)
# ...
#generate the second instance
ax2 = ax.twinx()
ax2.plot(hours, temperature, color="red", linewidth=3)
# ... set additional configuration for ax2
Both axes will share the same x-axes and the same fig, so make sure that before showing the plot to tight the layout, otherwise y-label might be clipped.
fig.tight_layout()
plt.show()
EDIT:
To handle both axes at the same time, you need to use the figure object, so use it to save them to a png and set the legend. legend() method need to receive the labels which you can set manually of on each ax.plot( ..., label='<label>')
get the current figure before plt.show()
Set the legend using the figure object.
Save the image using the figure object.
Show the image.
The code:
fig = plt.gcf()
fig.legend(loc='center left', bbox_to_anchor=(0.15, 1.07), fontsize=14, ncol=3)
fig.savefig('CS_Curtailment_CombinedDiagram.png',
edgecolor='black', dpi=400, bbox_inches='tight')
plt.show()

Related

How to remove a particular grid line?

please see the result graph image below.
I wish to remove only one major grid line at y-axis value of 10 (Blue horizontal line), and keep all other grid lines.
Is there a way to do that?
plt.rcParams['font.family'] = 'Arial'
fig, ax = plt.subplots(figsize=(14.78, 9.84))
plt.xlim(0, 105)
plt.ylim(0, 10)
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
ax.spines['top'].set_linewidth(0)
ax.spines['right'].set_linewidth(0)
# Grid setting
plt.grid(True, color='#0100FF', which="major", ls="-")
plt.grid(True, color='#0BC904', which="minor", ls="-")
plt.xlabel("Indicator Amplitude, %FSH", fontsize=28, labelpad=15)
plt.ylabel("Function Generator Output, V", fontsize=28, labelpad=15)
# Axis setting
plt.tick_params(which="major", labelsize=22, length=10, pad=10, width=1.5)
plt.tick_params(which="minor", length=8, width=1.5)
# Plot scatter & line
plt.plot(FSH_axis, x_value[2:], color='black', marker='^', linewidth=1.5, markersize=8, label="40 dB")
plt.plot(FSH_axis, y_value[2:], color='red', marker='o', linewidth=1.5, markersize=8, label="60 dB")
plt.plot(FSH_axis, z_value[2:], color='blue', marker='v', linewidth=1.5, markersize=8, label="80 dB")
plt.legend(loc=(1 / 16, 58 / 90), ncol=1, fontsize=20, frameon=True, framealpha=1, edgecolor="black")
plt.show()
We can catch all gridlines with get_ygridlines(), then access individual gridlines as Line2D objects to modify them:
from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator
plt.rcParams['font.family'] = 'Arial'
fig, ax = plt.subplots(figsize=(14.78, 9.84))
plt.xlim(0, 105)
plt.ylim(0, 10)
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
ax.spines['top'].set_linewidth(0)
ax.spines['right'].set_linewidth(0)
# Grid setting
plt.grid(True, color='#0100FF', which="major", ls="-")
plt.grid(True, color='#0BC904', which="minor", ls="-")
#this part is added
#set the last horizontal gridline invisible
ygridlines = ax.get_ygridlines()
gridline_of_interest = ygridlines[-1]
gridline_of_interest.set_visible(False)
plt.xlabel("Indicator Amplitude, %FSH", fontsize=28, labelpad=15)
plt.ylabel("Function Generator Output, V", fontsize=28, labelpad=15)
# Axis setting
plt.tick_params(which="major", labelsize=22, length=10, pad=10, width=1.5)
plt.tick_params(which="minor", length=8, width=1.5)
# Plot scatter & line
FSH_axis = [10, 40, 100]
plt.plot(FSH_axis, [1, 3, 2], color='black', marker='^', linewidth=1.5, markersize=8, label="40 dB")
plt.plot(FSH_axis, [2, 2, 3], color='red', marker='o', linewidth=1.5, markersize=8, label="60 dB")
plt.plot(FSH_axis, [2, 1, 1], color='blue', marker='v', linewidth=1.5, markersize=8, label="80 dB")
plt.legend(loc=(1 / 16, 58 / 90), ncol=1, fontsize=20, frameon=True, framealpha=1, edgecolor="black")
plt.show()
Sample output:
Of course, the corresponding get_xgridlines() also exists.

Creating a Dashboard of Graphs in Python

using matplotlib in Jupyter Notebook, I have already written code to produce a number of different graphs (example code below used to create some of my graphs). I would like to put all of these graphs into a dashboard. Is there a preferred method for my instance where I already have the graph produced and just want to plug it in to a dashboard template?
It seems like there are a number of different options (bokeh and plotly).
# multiple line plots
plt.plot( 'Week', 'ESI_1_2_3', data=SZ_ED_TOT, marker='o', color='blue', linewidth=2)
plt.plot( 'Week', 'ESI_4_5', data=SZ_ED_TOT, marker='o', color='red', linewidth=2)
plt.ylabel('Patient Count')
plt.xlabel('Week')
plt.xticks(rotation = 90)
plt.title('SZ Acuity Counts')
plt.gcf().set_size_inches(20, 8)
plt.legend()
plt.show()
# multiple line plots
plt.plot( 'Week', '%_1_2_3', data=UMC_ED_TOT, marker='o', color='blue', linewidth=2)
plt.plot( 'Week', '%_4_5', data=UMC_ED_TOT, marker='o', color='red', linewidth=2)
plt.ylabel('% of Patients')
plt.xlabel('Week')
plt.xticks(rotation = 90)
plt.title('UMC Acuity % Of Total Patients')
plt.gcf().set_size_inches(20, 8)
plt.legend()
plt.show()
#dual Y axis graph
ax = UMC_Cobmined.plot.bar(x='Week', y='Total', rot=90,color=(0.2, 0.4, 0.6, 0.6))
ax.set_xlabel('Week')
ax.set_ylabel('Total Volume')
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(),
UMC_Cobmined[['%_ESI_3','%_ESI_4','%_ESI_5']].values,
linestyle='-',
marker='o', linewidth=2.0)
ax2.set_ylabel('% LWBS By Acuity')
ax2.legend(["%_ESI_3", "%_ESI_4","%_ESI_5"]);
plt.title('UMC LWBS Acuity % by Volume')
plt.gcf().set_size_inches(20, 8)
plt.show()
Ideal example of what I would like my dashboard to look like:
You can achieve this by using a grid in matplotlib:
import matplotlib.pytplot as plt
fig = plt.figure()
grid = fig.add_gridspec(NUMBER_OF_GRID_COLUMNS, NUMBER_OF_GRID_ROWS)
and then add each plot to an axis:
ax1 = fig.add_subplot(grid[0, 0])
# add plot to ax1
ax1.plot(x,y)
ax1.title("Plot on ax1")
ax2 = fig.add_subplot(grid[1,0])
# add plot to ax2
ax2.plot(x,y)
ax2.title("Plot on ax2")
plt.show()
and so on

multiple axis not starting at zero

I Darw a graph with mutliple axix, have several questios:
why the left y-axsis is not satrting from zero. (I mean the zero point
is not at the begining of the y-axix).
I only want major grid for the x-axis (a major grid line for each week) but the code add a mjor
grid for the y-axix also.
How can i add minor grid for y-axix (the red one (ax2))
i want to change the color for the x-axis labels (Dates) color to black
import matplotlib.pyplot as plt
Hits= pd.read_excel("stackoverflow_example.xlsx", sheet_name="data")
fig=plt.figure(figsize=(20,10))
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.bar(Hits['Date'], Hits['Total'], width=0.35, color="b" )
ax.set_ylabel('Hits', color="b",size=16)
ax.yaxis.set_label_position('right')
ax.tick_params(axis='y', colors="b")
ax.tick_params(axis='x', colors="b", rotation=45)
ax.yaxis.tick_right()
ax2.plot(Hits['weeks'], Hits['Cases'], linewidth= 3.5, color="Red")
ax2.set_ylabel("Cases", color="Red",size=16)
ax2.tick_params(axis='y', colors="Red", size=16)
ax2.xaxis.set_ticks_position('top')
major_ticks = np.arange(0, 10, 1)
ax.set_xticks(major_ticks)
ax.grid(which='major', alpha=0.5)
plt.show()
My data
[
Graph:
If you want to start from zero, you can do that with 'ax2.set_ylim()'. After that, you can specify the axes for the grid. If the color is black, you can set color='k'.
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(20,10))
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.bar(Hits['Date'], Hits['Total'], width=0.35, color="b" )
ax.set_ylabel('Hits', color="b",size=16)
ax.yaxis.set_label_position('right')
ax.tick_params(axis='y', colors="b")
ax.tick_params(axis='x', colors="k", rotation=45)
ax.yaxis.tick_right()
ax2.plot(Hits['weeks'], Hits['Cases'], linewidth= 3.5, color="Red")
ax2.set_ylabel("Cases", color="Red",size=16)
ax2.tick_params(axis='y', colors="Red", size=16)
ax2.xaxis.set_ticks_position('top')
ax2.set_ylim(0,62) # update
major_ticks = np.arange(0, 10, 1)
ax.set_xticks(major_ticks)
ax.grid(which='major', axis='x', alpha=0.5) #update
ax2.grid(which='major', axis='y', alpha=0.5) # update
plt.show()

For scatterplot with matplotlib how to include in the legend gradient for dot size and colour?

I create two scatterplots with matplotlib in python with this code, the data for the code is here:
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
fig = plt.figure(figsize=(20,12))
ax1 = fig.add_subplot(111)
ax3 = ax1.twinx()
norm = Normalize(vmin=0.95*min(arr), vmax=1.05*max(arr))
ax1.scatter(x, y1, s=20, c=arr, cmap='Blues_r', norm=norm, marker='x', label='bla1')
ax3.scatter(x, y2, s=(20*(1.1-arr))**3.5, c=arr, cmap='Reds_r', norm=norm, marker='^', label='bla1')
The created fig. looks like this:
So, the dot size (in ax3) and the dot colour (in ax1 and ax3) are taken from arrays containing floats with all kinds of values in the range [0,1]. My question: How do I create a legend that displays the corresponding y-values for, let's say 5 different dot sizes and 5 different colour nuances?
I would like the legend to look like in the figure below (source here), but with the colour bar and size bar put into a single legend, if possible. Thanks for suggestions and code!
# using your data in dataframe df
# create s2
df['s2'] = (20*(1.1-df.arr))**3.5
fig = plt.figure(figsize=(20,12))
ax1 = fig.add_subplot(111)
ax3 = ax1.twinx()
norm = Normalize(vmin=0.95*min(df.arr), vmax=1.05*max(df.arr))
p1 = ax1.scatter(df.x, df.y1, s=20, c=df.arr, cmap='Blues_r', norm=norm, marker='x')
fig.colorbar(p1, label='arr')
p2 = ax3.scatter(df.x, df.y2, s=df.s2, c=df.arr, cmap='Reds_r', norm=norm, marker='^')
fig.colorbar(p2, label='arr')
# create the size legend for red
for x in [15, 80, 150]:
plt.scatter([], [], c='r', alpha=1, s=x, label=str(x), marker='^')
plt.legend(loc='upper center', bbox_to_anchor=(1.23, 1), ncol=1, fancybox=True, shadow=True, title='s2')
plt.show()
There's no legend for p1 because the size is static.
I think this would be better as two separate plots
I used Customizing Plot Legends: Legend for Size of Points
Separate
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(20, 10))
norm = Normalize(vmin=0.95*min(df.arr), vmax=1.05*max(df.arr))
p1 = ax1.scatter(df.x, df.y1, s=20, c=df.arr, cmap='Blues_r', norm=norm, marker='x')
fig.colorbar(p1, ax=ax1, label='arr')
p2 = ax2.scatter(df.x, df.y2, s=df.s2, c=df.arr, cmap='Reds_r', norm=norm, marker='^')
fig.colorbar(p2, ax=ax2, label='arr')
# create the size legend for red
for x in [15, 80, 150]:
plt.scatter([], [], c='r', alpha=1, s=x, label=str(x), marker='^')
plt.legend(loc='upper center', bbox_to_anchor=(1.2, 1), ncol=1, fancybox=True, shadow=True, title='s2')
plt.show()

Average line for bar chart in matplotlib

How do we draw an average line (horizontal) for a histogram in using matplotlib?
Right now, I'm able to draw the histogram without any issues.
Here is the code I'm using:
## necessary variables
ind = np.arange(N) # the x locations for the groups
width = 0.2 # the width of the bars
plt.tick_params(axis='both', which='major', labelsize=30)
plt.tick_params(axis='both', which='minor', labelsize=30)
ax2 = ax.twinx()
## the bars
rects1 = ax.bar(ind, PAAE1, width,
color='0.2',
error_kw=dict(elinewidth=2,ecolor='red'),
label='PAAE1')
rects2 = ax.bar(ind+width, PAAE2, width,
color='0.3',
error_kw=dict(elinewidth=2,ecolor='black'),
label='PAAE2')
rects3 = ax2.bar(ind+width+width, AAE1, width,
color='0.4',
error_kw=dict(elinewidth=2,ecolor='red'),
label='AAE1')
rects4 = ax2.bar(ind+3*width, AAE2, width,
color='0.5',
error_kw=dict(elinewidth=2,ecolor='black'),
label='AAE3')
maxi = max(dataset[2])
maxi1 = max(dataset[4])
f_max = max(maxi, maxi1)
lns = [rects1,rects2,rects3,rects4]
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc='upper center', ncol=4)
# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0, 100)
ax.set_ylabel('PAAE', fontsize=25)
ax2.set_ylim(0, f_max+500)
ax2.set_ylabel('AAE (mW)', fontsize=25)
xTickMarks = dataset[0]
ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=90, fontsize=25)
I want to plot the average line for PAAE 1, 2 and AAE 1, 2.
What should I be using to plot the average line?
If you'd like a vertical line to denote the mean use axvline(x_value). This will place a vertical line that always spans the full (or specified fraction of) y-axis. There's also axhline for horizontal lines.
In other works, you might have something like this:
ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)
As a more complete, but unnecessarily complex example (most of this is nicely annotating the means with curved arrows):
import numpy as np
import matplotlib.pyplot as plt
data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(-2, 1.5, 1000)
fig, ax = plt.subplots()
bins = np.linspace(-10, 5, 50)
ax.hist(data1, bins=bins, color='blue', label='Dataset 1',
alpha=0.5, histtype='stepfilled')
ax.hist(data2, bins=bins, color='green', label='Dataset 2',
alpha=0.5, histtype='stepfilled')
ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)
# Add arrows annotating the means:
for dat, xoff in zip([data1, data2], [15, -15]):
x0 = dat.mean()
align = 'left' if xoff > 0 else 'right'
ax.annotate('Mean: {:0.2f}'.format(x0), xy=(x0, 1), xytext=(xoff, 15),
xycoords=('data', 'axes fraction'), textcoords='offset points',
horizontalalignment=align, verticalalignment='center',
arrowprops=dict(arrowstyle='-|>', fc='black', shrinkA=0, shrinkB=0,
connectionstyle='angle,angleA=0,angleB=90,rad=10'),
)
ax.legend(loc='upper left')
ax.margins(0.05)
plt.show()

Categories