I am plotting 4 subplots on 1 figure with code below. When I try to plot the same plot in the notebook later just with fig I receive the same plot but with no white background, it is transparent. Any idea why it happens and what should I do to also get white background in next plot?
fig, axes = plt.subplots(figsize=(14, 10), nrows=2, ncols=2)
vec1 = np.random.randint(1,11,100)
vec2 = np.random.rand(100)
vec3 = np.random.randn(100)
vec4 = np.random.random(100)
axes[0, 0].plot(vec1, label='1')
axes[0, 1].hist(vec2, bins=20, edgecolor='k')
axes[1, 0].plot(vec3, label='3')
axes[1, 1].hist(vec4, bins=20, edgecolor='k')
axes[0][0].set_title("randint", fontsize=15)
axes[0][1].set_title("rand", fontsize=15)
axes[1][0].set_title("randn", fontsize=15)
axes[1][1].set_title("random", fontsize=15)
fig.legend(loc='upper left')
fig.suptitle("Losowe wektory", fontsize=18)
fig.subplots_adjust(left=0.1, bottom=0.05, right=0.9, top=0.9, wspace=0.15, hspace=0.35)
fig, axes = plt.subplots(figsize=(14, 10), nrows=2, ncols=2, facecolor='white')
Setting facecolor to white solves the problem, first I thought it is would be basically white and we have to set transparency to get it but it is otherwise as I can see.
Related
fig=plt.figure()
ax1=fig.add_axes([0,0,1,1])
ax2=fig.add_axes([0.2,0.5,0.4,0.4])
ax1.set_xlim([0,100])
ax1.set_ylim([0,10000])
ax2.set_xlim([20,22])
ax2.set_ylim([30,50])
ax1.set_ylabel('Z')
ax1.set_xlabel('X')
ax1.xaxis.set_major_locator(ticker.MultipleLocator(2000))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(20))
ax2.set_ylabel('Y')
ax2.set_xlabel('X')
ax2.xaxis.set_major_locator(ticker.MultipleLocator(5))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(0.5))
This is printing out the following plot.
Fixed tick locators, adjusted subplot positioning, organized code a bit, hid spines, added dashed y grid, increased tick label font sizes.
fig, ax1 = plt.subplots(figsize=(12,8))
ax2 = fig.add_axes([0.575,0.55,0.3,0.3])
ax1.set_xlim([0,100])
ax1.set_ylim([0,10000])
ax1.set_xlabel('X', fontweight='bold')
ax1.set_ylabel('Z', rotation=0, fontweight='bold')
ax1.xaxis.set_major_locator(ticker.MultipleLocator(20))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(1000))
ax1.grid(axis='y', dashes=(8,3), color='gray', alpha=0.3)
ax2.set_xlim([20,22])
ax2.set_ylim([30,50])
ax2.set_xlabel('X', fontweight='bold')
ax2.set_ylabel('Y', rotation=0, fontweight='bold')
ax2.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(5))
for ax in [ax1, ax2]:
[ax.spines[s].set_visible(False) for s in ['top','right']]
ax.tick_params(axis='both', labelsize=12, left=False, bottom=False)
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()
My goal is to create plot with four subplots, where the bottom two are really just empty boxes where I will display some text. Unfortunately, all of my efforts to remove the y and x axis tick marks and labels have failed. I'm still new to matplotlib so I'm sure there's something simple that I'm missing. Here's what I'm trying and what I get:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, sharex=False, sharey=True, figsize=(6,6))
fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.title('Neuron Length')
plt.xlabel('Strain')
plt.ylabel('Neuron Length (um)')
aIP = fig.add_subplot(223, frameon=False)
aIP.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5),
xycoords='axes fraction', va='center')
# First approach
aIP.axes.xaxis.set_ticks([])
aIP.axes.yaxis.set_ticks([])
# Second approach
ax = plt.gca()
ax.axes.yaxis.set_visible(False)
plt.show()
This is achieved by using plt.subplots() to draw four of them and remove the bottom left frame.
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(-np.pi, np.pi, 1000)
x1 = np.sin(2*t)
x2 = np.cos(2*t)
x3 = x1 + x2
fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(6,6), sharex=True, sharey=True)
axes[0,0].plot(t, x1, linewidth=2)
axes[0,1].plot(t, x2, linewidth=2)
axes[1,1].plot(t, x3, linewidth=2)
axes[1,0].axis('off') # off
axes[1,0].annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5), xycoords='axes fraction', va='center')
fig.suptitle('Neuron Length')
for ax in axes.flat:
ax.set(xlabel='Strain', ylabel='Neuron Length (um)')
plt.show()
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()
I wrote the following code below to do the following graph:
fig, ax = plt.subplots(figsize=(8, 6))
ax.patch.set_facecolor('white')
ax.plot(df.index, df.X1.values, 'b',
label='NMA', linewidth=1.5)
ax.set_ylabel('Index')
ax2 = ax.twinx()
ax2.plot(df.index, df.Y.values, 'r--',
label='Rate', linewidth=1.5)
ax2.set_ylabel('Rate')
lines = ax.get_lines() + ax2.get_lines()
lgd = ax.legend(lines, [line.get_label() for line in lines],
loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.15),
frameon=False)
ax.set_title('Economic Rate and Index',
weight='bold')
for i in range(5):
plt.axvspan(Dates['Peak'][i], Dates['Trough'][i],
facecolor='grey', alpha=0.5)
plt.grid(False)
plt.savefig('C:\\test.pdf',
bbox_extra_artists=(lgd,), bbox_inches='tight')
I am having a hard time to reproduce this figure in a subplot (2X2). The only thing I would change in each of the subplots is the blue line (X1 in df... for X2, X3...). How can I have a 2X2 subplot of the above graph? Of Course I would only keep one legend at the bottom of the subplots. Thanks for the help.
The data is here and the "Dates" to reproduce the gray bars here.
This is how you could create a 2x2 raster with twinx each:
import matplotlib.pyplot as plt
fig, ((ax1a, ax2a), (ax3a, ax4a)) = plt.subplots(2, 2)
ax1b = ax1a.twinx()
ax2b = ax2a.twinx()
ax3b = ax3a.twinx()
ax4b = ax4a.twinx()
ax1a.set_ylabel('ax1a')
ax2a.set_ylabel('ax2a')
ax3a.set_ylabel('ax3a')
ax4a.set_ylabel('ax4a')
ax1b.set_ylabel('ax1b')
ax2b.set_ylabel('ax2b')
ax3b.set_ylabel('ax3b')
ax4b.set_ylabel('ax4b')
plt.tight_layout()
plt.show()
Result: