Updating a plot after show - matplotlib

Say I have created a plot and then I show it
fig1 = plt.figure()
ax = fig1.add_subplot(111)
lt.plot(mat0[21:27,1],mat0[21:27,4],marker='s', label = "21")
lt.plot(mat0[21:27,1],mat0[21:27,3],marker='s', label = "23")
plt.plot(mat0[21:27,1],mat0[21:27,2],marker='s', label = "28")
pl.show()
I then realize that I have missed some lines to plot, how can I update the graph without going through all the process of plotting every single line again?

Related

Matplotlib doesn't show both datasets points on the figure when I want to create scatter plot with

I'm sure that I've done all things right but in the end the result I got is a sccatter plot that only shows the second datasets data.
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(train["ENGINESIZE"], train["CO2EMISSIONS"], color = "green")
ax1.scatter(test["ENGINESIZE"], test["CO2EMISSIONS"], color = "red")
plt.xlabel("Engine Size")
plt.ylabel("Emission")
plt.show()
Here You can see what's going on in my output in link below.
It shows only red data(test data) in the output.
Where is the "output link below", please? For now I can only imagine what you are describing.
Also it helps if both plots have the same axis. That is, both have the same x-axis and then they can vary on their y-axis.
If so:
fig, ax = plt.subplots()
df.plot(kind = 'scatter', x= train["ENGINESIZE"], y = train["CO2EMISSIONS"], color = {'g'}, ax = ax)
df.plot(kind = 'scatter', x= test["ENGINESIZE"], y = test["CO2EMISSIONS"], color = {'r'}, ax = ax)
plt.xlabel()

Matplotlib: Multiple plots with same layout (no automatic layout)

I am trying to make several pie charts that I can then transition between in a presentation. For this, it would be very useful for the automatic layouting to... get out of the way. The problem is that whenever I change a label, the whole plot moves around on the canvas so that it fits perfectly. I'd like the plot to stay centered, so it occupies the same area every time. I have tried adding center=(0,0) to ax.pie(), but to no avail.
Two examples:
Image smaller, left
Image larger, right
Instead of that effect, I'd like the pie chart to be in the middle of the canvas and have the same size in both cases (and I'd then manually make sure that the labels are on canvas by setting large margins).
The code I use to generate these two images is:
import matplotlib.pyplot as plt
import numpy as np
# Draw labels, from
# https://matplotlib.org/3.2.2/gallery/pie_and_polar_charts/pie_and_donut_labels.html#sphx-glr-gallery-pie-and-polar-charts-pie-and-donut-labels-py
def make_labels(ax, wedges, labs):
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
bbox=bbox_props,
zorder=0, va="center")
for i, p in enumerate(wedges):
if p.theta2-p.theta1 < 5:
continue
ang = (p.theta2 - p.theta1) / 2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
ax.annotate(labs[i], xy=(x, y),
xytext=(1.1*x,1.1*y),
horizontalalignment=horizontalalignment, **kw)
kw=dict(autoscale_on=False, in_layout=False, xmargin=1, ymargin=1)
fig, ax = plt.subplots(figsize=(3, 3), dpi=100, subplot_kw=kw)
wedges, texts = ax.pie(x=[1,2,3], radius=1,
wedgeprops=dict(width=1),
pctdistance=0.7,
startangle=90,
textprops=dict(fontsize=8),
center=(0, 0))
make_labels(ax, wedges, ["long text", "b", "c"])
#make_labels(ax, wedges, ["a", "b", "long text"])
plt.show()
Thanks a lot in advance!
How are you saving your figures? It looks like you may be using savefig(..., bbox_inches='tight') which automatically resized the figure to include all the artists.
If I run your code with fig.savefig(..., bbox_inches=None), I get the following output

Draw various plots in one figure

The image below shows, what i want, 3 different plots in one execution but using a function
enter image description here
enter image description here
I used the following code:
def box_hist_plot(data):
sns.set()
ax, fig = plt.subplots(1,3, figsize=(20,5))
sns.boxplot(x=data, linewidth=2.5, ax=fig[0])
plt.hist(x=data, bins=50, density=True, ax = fig[1])
sns.violinplot(x = data, ax=fig[2])
and i got this error:
inner() got multiple values for argument 'ax'
Besides the fact that you should not call a Figure object ax and an array of Axes object fig, your problem comes from the line plt.hist(...,ax=...). plt.hist() should not take an ax= parameter, but is meant to act on the "current" axes. If you want to specify which Axes you want to plot, you should use Axes.hist().
def box_hist_plot(data):
sns.set()
fig, axs = plt.subplots(1,3, figsize=(20,5))
sns.boxplot(x=data, linewidth=2.5, ax=axs[0])
axs[1].hist(x=data, bins=50, density=True)
sns.violinplot(x = data, ax=axs[2])

Polar axis in matplotlib

I'm trying to set the r-axis in a polar plot using Matplotlib. At this time, the best result I got is the following one :
I would like to modify three things :
draw a thicker line for the axis with labels,
add ticks to others r-axis,
move the legend outside of the plot.
I expect something like that :
Thanks for your help.
JD
'''
r = [0.07109986, 0.07186792, 0.07128804, 0.07093468, 0.11061314,\
0.11480423, 0.09913993, 0.13417775, 0.07485087, 0.07140557,\
0.08117919, 0.1235301 , 0.07109986]
theta = 2.0*np.pi*np.arange(len(r))/(len(r)-1)
titles = ['$a$','$\\alpha$','$b^{1}$','$b^{2}$',\
'$c^{1}_{1}$','$c^{1}_{2}$','$c^{1}_{3}$','$c^{1}_{4}$',\
'$c^{2}_{1}$','$c^{2}_{2}$','$c^{2}_{3}$','$c^{2}_{4}$']
fig = plt.figure()
ax = fig.add_subplot(111,polar='True')
ax.plot(theta,r)
ax.spines['polar'].set_visible(False)
ax.set_theta_zero_location(loc='N')
ax.set_xticks(np.arange(0,2.0*np.pi,2.0*np.pi/len(titles)))
ax.set_xticklabels(titles)
ax.yaxis.grid(False)
ax.set_rlabel_position(0)
plt.tick_params(axis='y',labelsize=12)
plt.show()
'''

Matplotlib Subplot Labels Disappear

I want to prepare some hexbin plots from Pandas. My initial code is:
fig = plt.figure(figsize=(11,8))
ax1 = fig.add_subplot(111)
df2.plot(kind='hexbin', x='var1', y='var2', C='var3', reduce_C_function=np.median, gridsize=25,vmin=0, vmax=40,ax=ax1)
ax1.set_xlim([-5,2])
ax1.set_ylim([0,7])
However when I change this to:
fig = plt.figure(figsize=(11,8))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
And plot create four subplots similar to the first example it turns off the xlabels and xticklabels.
What code to I need to switch them back on? And is this something I can do as a defaults?