First of all, i'm sorry for my bad english.
When I try to insert grid in a graph created with plt.subplots, grid's lines don't appear if they are on axis number positions. This behaviour happens both for x-axis and for y-axis. I show my code:
pnt = listaPnt[i]
work = ax.flat[i]
im = work.imshow(lista[i], origin='lower', vmin=0, vmax=1, cmap=newcmp, extent=[0,mu_lim, 0,mu_lim])
work.plot(line, '-', color='grey', linewidth=0.8)
work.plot(line-line*0.10, '-', color='grey', linewidth=0.8)
work.plot(line+line*0.10, '-', color='grey', linewidth=0.8)
work.plot(line-line*0.25, '--', color='grey', linewidth=0.8)
work.plot(line+line*0.25, '--', color='grey', linewidth=0.8)
work.plot(pnt[:,1], pnt[:,0], '-', color='black', linewidth=1.5)
work.plot(pnt[:,1], pnt[:,0]-pnt[:,0]*0.25, '-', color='blue', linewidth=1.5)
work.plot(pnt[:,1], pnt[:,0]+pnt[:,0]*0.25, '-', color='blue', linewidth=1.5)
grid_x_ticks = np.arange(0, mu_lim, mu_lim/bins)
grid_y_ticks = np.arange(0, mu_lim, mu_lim/bins)
work.set_xticks(grid_x_ticks , minor=True
work.set_yticks(grid_y_ticks , minor=True)
work.grid(which='minor', alpha=0.1, linestyle='-', color='b')
work.set_ylabel('$\mu}$', fontsize='30')
work.set_xlabel('$\mu_{R}$', fontsize='30')
work.set_title('$z_s = '+str(zs)+'$'+stringa[i],
...
This processes are in a for cycle. The results is in figure. Can I resolve this problem?Every square has counts, the scale of colors is on the right
Related
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
I would like to shade the area under the kdeplot below the value -1.64.
I drew the kdeplot and a vertical line at -1.64.
How do I fill the triangular area between the kdeplot, the x-axis, and the vertical line?
Also, I would like the height of the orange vertical line to just reach the kdeplot.
fig, ax = plt.subplots(nrows=2, ncols=2,figsize=(12,6), tight_layout=True, sharex=True, sharey=True)
sns.kdeplot(pop_norm.fev1_z, ax=ax[0,0], legend=False)
ax[0,0].axvline(x=pop_norm.fev1_z.mean(), linestyle = '--', alpha =0.5)
ax[0,0].axvline(x=-1.64, linestyle = '-', color = palette[1], alpha =0.5)
ax[0,0].set_xlabel("FEV1 z-score")
ax[0,0].set_ylabel("Population density")
sns.kdeplot(pop_norm.fvc_z, ax=ax[0,1], legend=False)
ax[0,1].axvline(x=pop_norm.fvc_z.mean(), linestyle = '--', alpha =0.5)
ax[0,1].axvline(x=-1.64, linestyle = '-', color = palette[1], alpha =0.5)
ax[0,1].set_xlabel("FVC z-score")
sns.kdeplot(pop_norm.fev1fvc_z, ax=ax[1,0], legend=False)
ax[1,0].axvline(x=pop_norm.fev1fvc_z.mean(), linestyle = '--', alpha =0.5)
ax[1,0].axvline(x=-1.64, linestyle = '-', color = palette[1], alpha =0.5)
ax[1,0].set_xlabel("FEV1/FVC z-score")
ax[1,0].set_ylabel("Population density")
sns.kdeplot(pop_norm.fef2575_z, ax=ax[1,1], legend=False)
ax[1,1].axvline(x=pop_norm.fef2575_z.mean(), linestyle = '--', alpha =0.5)
ax[1,1].axvline(x=-1.64, linestyle = '-', color = palette[1], alpha =0.5)
ax[1,1].set_xlabel("FEF 25-75% z-score")
You can extract the curve of the kde by extracting the x and y data from the last lines element in the subplot.
These x and y can be used both to interpolate the curve height at given x values, and as parameters for fill_between().
Here is an example with one subplot:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
pop_norm_fev1_z = np.random.normal(-.004, .01, 500).cumsum()
fig, ax = plt.subplots(figsize=(12, 6))
sns.kdeplot(pop_norm_fev1_z, ax=ax, legend=False)
x = ax.lines[-1].get_xdata()
y = ax.lines[-1].get_ydata()
mean = pop_norm_fev1_z.mean()
ax.vlines(mean, 0, np.interp(mean, x, y), linestyle='--', alpha=0.5)
x_special = -1.64
ax.vlines(x_special, 0, np.interp(x_special, x, y), linestyle='-', color='crimson', alpha=0.5)
ax.fill_between(x, 0, y, where=x < x_special, color='gold', alpha=0.3)
plt.show()
I want to plot some data I have (square wave signals) in a subplot but I want to remove the axis for better visualization. This results in not having a ylabel. I thought I could add a simple text() so I could manually insert the text I want, but I can't seem to be able to use negative values for the y axis (as I could without a subplot). The code I thought would work was:
fig, (ax1, ax2, ax3, ax4, ax5, ax6)= plt.subplots(6,1)
#plot
ax1.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.clk_y, linewidth=2, color='black')
ax2.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.clkbar_y, linewidth=2, color='black')
ax3.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q1_y, linewidth=2, color='C0')
ax4.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q2_y, linewidth=2, color='C1')
ax5.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q1bar_y, linewidth=2, color='C2')
ax6.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q2bar_y, linewidth=2, color='C3')
#axis
ax1.axis('off')
ax2.axis('off')
ax3.axis('off')
ax4.axis('off')
ax5.axis('off')
ax6.axis('off')
#text
ax1.text(-1.5, 2, 'MyText')
If i try the last line as ax1.text(0, 2, 'MyText') it works fine, but the placement of the text is not the one I want. I suppose this comes from the size my plot is allowed to have and I would need to change it, how to do so?
EDIT
This is what I obtain hiding the axis manually (which can allow me to insert a ylabel). This is what I really want as plot obtained from the coded posted above by commenting ax1.text(-1.5, 2, 'MyText')
You can use fig instead of the ax1 to place your text. The arguments 0.05, 0.6 are the x and y coordinates in relative scale. You can choose them as per your taste.
Complete answer
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6,1)
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
ax1.plot(x, y, linewidth=2, color='black')
ax2.plot(x, y, linewidth=2, color='black')
ax3.plot(x, y, linewidth=2, color='C0')
ax4.plot(x, y, linewidth=2, color='C1')
ax5.plot(x, y, linewidth=2, color='C2')
ax6.plot(x, y, linewidth=2, color='C3')
# Hiding axis
for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
ax.axis('off')
fig.text(0.05, 0.6, 'MyText', rotation=90, fontsize=20)
plt.show()
I have a python script that has 3 functions that plot data. 2 of them show gridlines by using ax.grid(b=True). One however, doesn't. Even after I spammed ax.grid(b=True) all over the place... I must be doing something wrong, but what?
def plotMSEProgress(times, bestScores, scores, xsplit=0, window=1):
plot, ax = plt.subplots(figsize=(20,10), num=1)
ax.grid(b=True, which='both')
# plot = plt.figure(window)
plt.ion()
plt.minorticks_on()
ax.grid(b=True, which='both')
plt.show()
plt.clf()
if xsplit:
plt.axvline(x=xsplit, color='g')
plot = plt.plot_date(times, bestScores, '-', label="best score")
plot = plt.setp(plot, color='y', linewidth=1.0)
plot = plt.plot_date(times, scores, '-', label="score")
plot = plt.setp(plot, color='b', linewidth=1.0)
ax.grid(b=True, which='both')
plt.xlabel('time')
plt.ylabel('MSE')
plt.suptitle('MSE over time', fontsize=16)
plt.legend()
ax.grid(b=True, which='both')
plt.draw()
ax.grid(b=True, which='both')
plt.pause(0.001)
ax.grid(b=True, which='both')
plt.plot()
ax.grid(b=True, which='both')
Maybe it has something to do with plt.ion() ? Because I don't have that in the othe plotting functions that do show the grid.
I already tried this and this by adding the plt.minorticks_on(), but to no avail sadly.
Is there something obvious I'm missing? Or is there some other hidden incompatibility?
Screenshot of plot as requested:
Add in a call to plt.grid() inside your function, and remove extraneous code:
import matplotlib.pyplot as plt
import datetime
def plotMSEProgress(times, bestScores, scores, xsplit=0, window=1):
plot, ax = plt.subplots(figsize=(20,10), num=1)
plt.ion()
plt.clf()
if xsplit:
plt.axvline(x=xsplit, color='g')
plot = plt.plot_date(times, bestScores, '-', label="best score")
plot = plt.setp(plot, color='y', linewidth=1.0)
plot = plt.plot_date(times, scores, '-', label="score")
plot = plt.setp(plot, color='b', linewidth=1.0)
plt.minorticks_on()
plt.grid(which='major')
plt.grid(which='minor', linestyle = ':')
plt.xlabel('time')
plt.ylabel('MSE')
plt.suptitle('MSE over time', fontsize=16)
plt.legend(loc=2)
plt.draw()
plt.pause(0.001)
# Generate example data
base = datetime.datetime.today()
times = [base + datetime.timedelta(seconds=x) for x in range(0, 100)]
scores = np.random.rand(len(times))*30
bestScores = np.random.rand(len(times))*5
# Generate plot dynamically
for i in range(len(times)):
plotMSEProgress(times[0:i], bestScores[0:i], scores[0:i], xsplit=0, window=1)
This code generates a plot and dynamically updates it, all while showing the gridlines the whole time.
I think you have some unnecessary codes, which creates multiple plots. The first plot you had is empty but with grids and the later plots contain the data, but not the grids.
Try the code below. I commented some of your scripts and made it work.
def plotMSEProgress(times, bestScores, scores, xsplit=0, window=1):
plot, ax = plt.subplots(figsize=(20,10), num=1)
ax.grid(b=True, which='both')
# plot = plt.figure(window)
plt.ion()
plt.minorticks_on()
ax.grid(b=True, which='both')
# plt.show()
# plt.clf()
if xsplit:
plt.axvline(x=xsplit, color='g')
plot = plt.plot(times, bestScores, '-', label="best score") # you can change it back to plot_date
plot = plt.setp(plot, color='y', linewidth=1.0)
plot = plt.plot(times, scores, '-', label="score") # you can change it back to plot_date
plot = plt.setp(plot, color='b', linewidth=1.0)
ax.grid(b=True, which='both')
plt.xlabel('time')
plt.ylabel('MSE')
plt.suptitle('MSE over time', fontsize=16)
plt.legend()
ax.grid(b=True, which='both')
plt.draw()
ax.grid(b=True, which='both')
plt.pause(0.001)
ax.grid(b=True, which='both')
# plt.plot()
ax.grid(b=True, which='both')
times = list(range(0,100))
bestScores = list(range(100,200))
scores = list(range(150,250))
xsplit=0
window=1
plotMSEProgress(times, bestScores, scores, xsplit=0, window=1)
fig1 = figure()
ax = fig1.add_subplot(111, autoscale_on = False)
ax.plot(data[:,0]*1E6, data[:,3]
,data[:,0]*1E6, data[:,4],'r')
plt.xlabel('Time (us)')
plt.ylabel('Voltage (V)')
plt.title('Time')
plt.grid()
ax.annotate('axes center', xy=(.5, .5), xycoords='axes fraction',
horizontalalignment='center', verticalalignment='center')
plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.savefig('Time.png',orientation='landscape', pad_inches=0.1)
plt.clf()
The plot disappears after annotating. Only thing that is left after saving is the annotation. Can someone give a suggestion how to save it after annotating.