A polar plot as a subplot within another plot - python

I just want to plot a subplot inside another plot:
As you can see, in this code I tried to plot this polar plot inside the other plot, but I can't set the size and place of the plot one:
from matplotlib.gridspec import GridSpec
time = np.linspace(0, 10, 1000)
height = np.sin(time)
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))
fig = plt.figure(figsize=(10, 5))
gs = GridSpec(nrows=1, ncols=2)
ax2 = fig.add_subplot(gs[:, 1])
ax2.plot(time, score)
ax3 = fig.add_subplot(111,polar=True)
ax3.set_theta_zero_location("N")
ax3.plot(0-1.5708, 0,'o', linewidth=2,color="k")
theta1 = np.linspace(-0.48332530310852967-1.5708,0.48332530310852967-1.5708, 100)
ax3.fill_between(theta1, -0.1, +0.3, color='r')
theta2 = np.linspace(0.48332530310852967-1.5708,1.449975909325589-1.5708, 100)
ax3.fill_between(theta2, -0.1, +0.3, color='b')
theta3 = np.linspace(1.449975909325589-1.5708,2.4166265155426485-1.5708, 100)
ax3.fill_between(theta3, -0.1, +0.3, color='r')
theta4 = np.linspace(2.4166265155426485-1.5708,3.3832771217597077-1.5708, 100)
ax3.fill_between(theta4, -0.1, +0.3, color='b')
theta5 = np.linspace(3.3832771217597077-1.5708,3.870223983066126-1.5708, 100)
ax3.fill_between(theta5, -0.1, +0.3, color='g')
theta6 = np.linspace(3.870223983066126-1.5708,4.836874589283185-1.5708, 100)
ax3.fill_between(theta6, -0.1, +0.3, color='r')
theta6 = np.linspace(4.836874589283185-1.5708,5.803525195500244-1.5708, 100)
ax3.fill_between(theta6, -0.1, +0.3, color='b')
#ax3.annotate("{}".format(k), xy=[i, j], fontsize=9)
ax3.set_ylim(-10,1)
#ax3.set_xticks(np.linspace(0,2*np.pi,19)[:-1])
#ax3.set_rlabel_position(-47.5) # Move radial labels away from plotted line
ax3.grid(True)
plt.show()
what I have
what I want to have :

from matplotlib.gridspec import GridSpec
from mpl_toolkits.axes_grid.inset_locator import (inset_axes, InsetPosition,
mark_inset)
time = np.linspace(0, 10, 1000)
height = np.sin(time)
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))
fig = plt.figure(figsize=(10, 5))
gs = GridSpec(nrows=1, ncols=2)
ax2 = fig.add_subplot(gs[:, 0])
ax2.plot(time, score)
ax3 = fig.add_axes([0.1, 0.47, 0.25, 0.35], polar=True)
#ax3 = ax2.inset_axes([0.4,0.4,0.2,0.2], subplot_kw={'projection': 'polar'})
ax3.set_theta_zero_location("N")
ax3.plot(0-1.5708, 0,'o', linewidth=2,color="k")
theta1 = np.linspace(-0.48332530310852967-1.5708,0.48332530310852967-1.5708, 100)
ax3.fill_between(theta1, -0.1, +0.3, color='r')
theta2 = np.linspace(0.48332530310852967-1.5708,1.449975909325589-1.5708, 100)
ax3.fill_between(theta2, -0.1, +0.3, color='b')
theta3 = np.linspace(1.449975909325589-1.5708,2.4166265155426485-1.5708, 100)
ax3.fill_between(theta3, -0.1, +0.3, color='r')
theta4 = np.linspace(2.4166265155426485-1.5708,3.3832771217597077-1.5708, 100)
ax3.fill_between(theta4, -0.1, +0.3, color='b')
theta5 = np.linspace(3.3832771217597077-1.5708,3.870223983066126-1.5708, 100)
ax3.fill_between(theta5, -0.1, +0.3, color='g')
theta6 = np.linspace(3.870223983066126-1.5708,4.836874589283185-1.5708, 100)
ax3.fill_between(theta6, -0.1, +0.3, color='r')
theta6 = np.linspace(4.836874589283185-1.5708,5.803525195500244-1.5708, 100)
ax3.fill_between(theta6, -0.1, +0.3, color='b')
#ax3.annotate("{}".format(k), xy=[i, j], fontsize=9)
ax3.set_ylim(-10,1)
#ax3.set_xticks(np.linspace(0,2*np.pi,19)[:-1])
#ax3.set_rlabel_position(-47.5) # Move radial labels away from plotted line
ax3.grid(True)
plt.show()

Related

Round lines in Matplotlib

I would like to have a diagramm in Matplotlib with a curved (smooth) lines. So the individual points should be connected by round lines. Further, I would like to have no values on the y-line (only the description). Here is the coode:
from matplotlib import pyplot as plt
%matplotlib inline
load = [0.0, 0.1, 0.5, 0.7, 0.4, 0.55, 0.4, 0.3, 0.4, 0.5, 0.65, 0.75, 0.768, 0.75, 0.65, 0.5, 0.4, 0.3, 0.2, 0.15, 0.25, 0.4, 0.5, 0.4, 0.5]
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="default", 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, 1)
plt.xticks(hours, labels=labels, rotation=90)
ax.tick_params(axis='both', which='major', labelsize=0)
# (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.
for item in [fig, ax]:
item.patch.set_visible(False)
plt.savefig('CS_Curtailment_ElectricalLoad_NoFrame.png', edgecolor='black', dpi=400, bbox_inches='tight')
plt.show()
I think the attribute "drawystyle" might be changed. But I do not know how.
I'd appreciate every comment and would be thankful for your help.
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import numpy as np
load = [0.0, 0.1, 0.5, 0.7, 0.4, 0.55, 0.4, 0.3, 0.4, 0.5, 0.65, 0.75, 0.768, 0.75, 0.65, 0.5, 0.4, 0.3, 0.2, 0.15, 0.25, 0.4, 0.5, 0.4, 0.5]
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"]
f = interp1d(hours, load)
f2 = interp1d(hours, load, kind='cubic')
xnew = np.linspace(0, 24, num=500, endpoint=True)
plt.xticks(np.arange(0, 25, step=1)) # Set label locations.
plt.xticks(np.arange(25), labels) # Set text labels.
plt.xticks(np.arange(25), labels, rotation=90)
plt.plot(hours, load, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic'], loc='best')
plt.ylabel("Electrical power in W", fontsize=14, labelpad=8)
plt.xlabel("Time of day", fontsize=14, labelpad=8)
plt.show()
plt.xticks(np.arange(0, 25, step=1)) # Set label locations.
plt.xticks(np.arange(25), labels) # Set text labels.
plt.xticks(np.arange(25), labels, rotation=90)
plt.plot(xnew, f2(xnew), color="green", linewidth=3)
plt.legend(['cubic'], loc='best')
plt.ylabel("Electrical power in W", fontsize=14, labelpad=8)
plt.xlabel("Time of day", fontsize=14, labelpad=8)
plt.show()
Edit-1: x-axis labels are 90 degree rotated
Plotting figure using cubic interpolation:
Edit-2: To hide to y-axis variables, we can add plt.tick_params(labelleft=False) before plt.show().
Plotted figure is shown below:
Edit-3: Plotting new load.
We can plot new load list by adding these lines into the code.
load_2 = [0.0, 0.3, 0.2, 0.8, 0.1, 0.5, 0.2, 0.7, 0.4, 0.5, 0.34, 0.45, 0.768, 0.9, 0.25, 0.55, 0.2, 0.3, 0.2, 0.65, 0.25, 0.4, 0.2, 0.4, 0.5]
f3 = interp1d(hours, load_2, kind='cubic', fill_value="extrapolate")
xnew = np.linspace(0, 24, num=500, endpoint=True)
plt.xticks(np.arange(0, 25, step=1)) # Set label locations.
plt.xticks(np.arange(25), labels) # Set text labels.
plt.xticks(np.arange(25), labels, rotation=90)
plt.plot(xnew, f3(xnew), color="red", linewidth=3)
plt.legend(['cubic'], loc='best')
plt.ylabel("Electrical power in W", fontsize=14, labelpad=8)
plt.xlabel("Time of day", fontsize=14, labelpad=8)
plt.tick_params(labelleft=False)
plt.show()
Edit-4: Plotting two lines in one figure:
xnew = np.linspace(0, 24, num=500, endpoint=True)
plt.xticks(np.arange(0, 25, step=1)) # Set label locations.
plt.xticks(np.arange(25), labels) # Set text labels.
plt.xticks(np.arange(25), labels, rotation=90)
plt.plot(xnew, f2(xnew), color="blue", linewidth=3)
plt.plot(xnew, f3(xnew), color="red", linewidth=3)
plt.legend(['load-1', 'load-2'], loc='best')
plt.ylabel("Electrical power in W", fontsize=14, labelpad=8)
plt.xlabel("Time of day", fontsize=14, labelpad=8)
plt.tick_params(labelleft=False)
plt.show()
Edit-5: To fill the area under curve of the two lines, we need to add following lines:
plt.fill_between(xnew, f2(xnew), color="blue", alpha=0.30, edgecolor=None)
plt.fill_between(xnew, f3(xnew), color="red", alpha=0.30, edgecolor=None)
Plotted figure is shown below:
I don't have any experience with curve fitting, but I've looked at customizing it based on this answer. np.polyfit(x,y, deg)
from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline
load = [0.0, 0.1, 0.5, 0.7, 0.4, 0.55, 0.4, 0.3, 0.4, 0.5, 0.65, 0.75, 0.768, 0.75, 0.65, 0.5, 0.4, 0.3, 0.2, 0.15, 0.25, 0.4, 0.5, 0.4, 0.5]
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"]
poly = np.polyfit(hours, load, 8)
poly_y = np.poly1d(poly)(hours)
fig = plt.figure(linewidth=1, figsize=(9, 5))
ax = plt.gca()
# ax.plot(hours, load, color="goldenrod", ls='-', linewidth=3) # <- drawstyle argument.
ax.plot(hours, poly_y, color="goldenrod", ls='-', linewidth=3)
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, 1)
ax.set_xticks(hours)
ax.set_xticklabels(labels, rotation=90)
ax.set_yticks([])
ax.tick_params(axis='both', which='major', labelsize=10)
# (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.
# for item in [fig, ax]:
# item.patch.set_visible(False)
plt.savefig('CS_Curtailment_ElectricalLoad_NoFrame.png', edgecolor='black', dpi=400, bbox_inches='tight')
plt.show()

Issue with setting upper limit to y-xis on graph with matplotlib

The following code returns the nice graph provided here:
.
However, when I add a line code such as ax.set_ylim(ymax=14) I get the following graph:
.
Clearly there is something wrong. Could anyone help me figure out what?
Thanks!
fig, ax = plt.subplots(figsize=(15, 10))
# Set bins for histograms:
bins = np.arange(0, 40+0.5, 1)
# set interval on this bins for curve fitting:
xplot = np.linspace(min(bins), max(bins), 100)
# -- make a histogram
ax.grid(axis='y', zorder=0)
plt.axvline(x=af_farm_w_speedb.mean(), color='black', linestyle='dashed', linewidth=2, label = "Mean speed at control")
plt.axvline(x=af_farm_w_speedw.mean(), color='red', linestyle='dashed', linewidth=2, label = "Mean speed at treatment")
ax.hist([af_farm_w_speedb, af_farm_w_speedw], bins=bins, density=True, alpha = 1, align='left', zorder=1, rwidth=0.8, color=['lightsteelblue','grey'], label = ['Records at control', 'Records at treatment'])
ax.tick_params(axis='both', which='major', labelsize=30)
ax.set_yticklabels([0, 2, 4, 6, 8, 10, 12])
ax.set_title('Post-farm wind speed distribution', fontsize=35)
(scale, a, shape, c) = stats.exponweib.fit(af_farm_w_speedw, f0=1, floc=0)
ax.plot(xplot, stats.exponweib.pdf(xplot, *stats.exponweib.fit(af_farm_w_speedb, 1, 1, scale=1, loc=0)), zorder=3, color = "black", linewidth=1.6, label="Weibull fit at control")
ax.plot(xplot, stats.exponweib.pdf(xplot, *stats.exponweib.fit(af_farm_w_speedw, 1, 1, scale=1, loc=0)), zorder=3, color = "red", linewidth=1.6, label="Weibull fit at treatment")
fig.text(0.6, 0.55, "Mean speed at treatment: {:.4g}".format(af_farm_w_speedw.mean()), fontsize=18)
fig.text(0.6, 0.6, "Mean speed at control: {:.4g}".format(af_farm_w_speedb.mean()), fontsize=18)
ax.legend(prop=dict(size=18))

Removing axes and lining up a subplot

I have produced a graph with two subplots and am trying to add a histogram to the end of the residuals plot but am unable to remove the x-axis of the histogram plot and get it to line up with the end of the residual plot.
Here is a copy of my current code:
#graph with histogram and std error plot thing
fig1 = plt.figure(figsize =(9.6,7.2))
ax = fig1.add_axes((0.2,0.4,.75,.6))
ax.errorbar(xval, yval*1000, yerr=yerr*1000, xerr=xerr, marker='x', linestyle='None')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
# Axis labels
plt.xlabel('Height (m)', fontsize = 12)
plt.ylabel('dM/dt (g $s^{-1}$) × $10^{3}$', fontsize = 12)
# Generate best fit line using model function and best fit parameters, and add to plot
fit_line=model_funct(xval, [a_soln, b_soln])
plt.plot(xval, fit_line*1000)
# Set suitable axis limits: you will probably need to change these...
#pyplot.xlim(-1, 61)
#pyplot.ylim(65, 105)
# pyplot.show()
ax2 = fig1.add_axes((0.2,0.2,.75,.2)) #start frame1 at 0.2, 0.4
plt.xlabel("Height of Water (m)", fontsize = 12)
plt.ylabel("Normalised\nResiduals", fontsize = 12) #\n is used to start a new line
ax2.plot(h,normalised_residuals,"x", color = "green")
plt.axhline(0, linewidth=1, linestyle="--", color="black")
plt.savefig("Final Graph with added parts.png", dpi = 500)
ax2.axhspan(ymin = -np.std(normalised_residuals), ymax = np.std(normalised_residuals), color = 'gray', alpha =0.5)
ax3 = fig1.add_axes((1,0.2,0.2,0.2))
ax3.hist(normalised_residuals, bins=8, orientation="horizontal")
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.spines['left'].set_visible(False)
ax3.yaxis.set_ticks_position('left')
ax3.xaxis.set_ticks_position('bottom')
and here is a picture of my graph currently:
An example with random data. Using tick_params and manually setting both ylim and the histogram range, did the trick.
import matplotlib.pyplot as plt
import numpy as np
fig1 = plt.figure(figsize=(20, 15))
ax = fig1.add_axes((0.2, 0.4, .75, .6))
ax2 = fig1.add_axes((0.2, 0.2, .75, .2))
ax3 = fig1.add_axes((.95, 0.2, 0.2, 0.2))
xval = (np.linspace(0.02, 0.15, 20)
+ (np.random.default_rng(0).random(20) - 0.5) / 30)
yval = 2 * xval + 0.08
xerr = (np.random.default_rng(0).random(20) * 2 - 1) / 60
yerr = (np.random.default_rng(1).random(20) * 2 - 1) / 60
ax.errorbar(xval, yval, yerr=yerr, xerr=xerr, marker='x', linestyle='None')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(labelbottom=False)
ax.set_xlabel('Height (m)', fontsize=12)
ax.set_ylabel('dM/dt (g $s^{-1}$) × $10^{3}$', fontsize=12)
ax2.plot(xval, xerr, 'x', color='green')
ax2.axhline(0, linewidth=1, linestyle='--', color='black')
ax2.axhspan(ymin=-np.std(xerr), ymax=np.std(xerr), color='gray', alpha=0.5)
ax2.set_xlabel('Height of Water (m)', fontsize=12)
ax2.set_ylabel('Normalised\nResiduals', fontsize=12)
resLim = ax2.get_ylim()
ax3.hist(xerr, bins=8, orientation='horizontal', range=resLim, rwidth=0.9)
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.spines['left'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.tick_params(labelbottom=False, labelleft=False, bottom=False, left=False)
ax3.set_ylim(resLim)
fig1.savefig('so.png', bbox_inches='tight')

Move table position matplotlib python

I have created a figure that displays a shape and table using matplotlib. The problem is how its produced. They overlap each other. The shape is to scale so I don't want to alter it. I was wondering how I can alter the overall size of the plot or move the position of the table.
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots(figsize = (10,6))
ax.axis('equal')
plt.style.use('ggplot')
ax.grid(False)
xy = 0,0
circle = mpl.patches.Circle(xy, 160, lw = 3, edgecolor = 'black', color = 'b', alpha = 0.1, zorder = 5)
ax.add_patch(circle)
col_labels=['A','B','C','D','E']
row_labels=['diff','total']
table_vals=[['','','','',''],['','','','','']]
the_table = plt.table(cellText=table_vals,
colWidths = [0.05]*5,
rowLabels=row_labels,
colLabels=col_labels,
bbox = [0.8, 0.4, 0.2, 0.2])
ax.autoscale()
plt.show()
Add the bbox argument with your table. (instead of loc)
the_table = plt.table(cellText=table_vals,
colWidths = [0.05]*5,
rowLabels=row_labels,
colLabels=col_labels,
bbox = [0.2, 0.4, 0.4, 0.02])
The bbox argument takes 4 inputs: X, Y, Width, Height. Thus X and Y are the coordinates of the bottom left corner. Above, the height was far too small.
EDIT: Create room to play with
The idea is to make the ax smaller in the same manner.
box = ax.get_position()
a.set_position([box.x0, box.y0, box.width * 0.9, box.height])
EDIT 2: Trying to put the table on the right. As I said, you need to play with the box values, took me about 10 tries to get this. I'm using spyder as an IDE, so it's really fast.
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots(figsize = (10,6))
ax.axis('equal')
plt.style.use('ggplot')
ax.grid(False)
xy = 0,0
circle = mpl.patches.Circle(xy, 160, lw = 3, edgecolor = 'black', color = 'b', alpha = 0.1, zorder = 5)
ax.add_patch(circle)
col_labels=['A','B','C','D','E']
row_labels=['diff','total']
table_vals=[['','','','',''],['','','','','']]
the_table = plt.table(cellText=table_vals,
colWidths = [0.05]*5,
rowLabels=row_labels,
colLabels=col_labels,
bbox = [1.1, 0.5, 0.35, 0.1])
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.autoscale()
plt.show()
Output:
Position the table outside the axes
You may use loc="right" to position the table right of the axes. Something like fig.subplots_adjust(right=0.8) will leave enough space for it.
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('ggplot')
fig, ax = plt.subplots(figsize = (10,6))
fig.subplots_adjust(right=0.8)
ax.axis('equal')
ax.grid(False)
xy = 0,0
circle = mpl.patches.Circle(xy, 160, lw = 3, edgecolor = 'black',
facecolor = 'b', alpha = 0.1, zorder = 5)
ax.add_patch(circle)
col_labels=['A','B','C','D','E']
row_labels=['diff','total']
table_vals=[['','','','',''],['','','','','']]
the_table = plt.table(cellText=table_vals,
colWidths = [0.05]*5,
rowLabels=row_labels,
colLabels=col_labels,
loc='right', zorder=3)
ax.autoscale()
plt.show()
Put the table in its own axes
You may put the table in a new axes next to the existing one. The advantage is that there is no need to then play with the column width or subplot parameters.
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('ggplot')
fig, (ax, ax_table) = plt.subplots(ncols=2, figsize = (10,6),
gridspec_kw=dict(width_ratios=[3,1]))
ax.axis('equal')
ax_table.axis("off")
ax.grid(False)
xy = 0,0
circle = mpl.patches.Circle(xy, 160, lw = 3, edgecolor = 'black',
facecolor = 'b', alpha = 0.1, zorder = 5)
ax.add_patch(circle)
col_labels=['A','B','C','D','E']
row_labels=['diff','total']
table_vals=[['','','','',''],['','','','','']]
the_table = ax_table.table(cellText=table_vals,
rowLabels=row_labels,
colLabels=col_labels,
loc='center')
ax.autoscale()
plt.show()

Inset graph, when using a legend placed outside the parent graph

I am trying to inset a graph inside the parent graph following the accepted answer here.
However, the plotting framework I am using is quite different:
1) First of all, the Legend is located outside the graph, for which I have followed the second answer posted here, i.e. via shrinking the parent graph:
plt.figure()
# Shrink current axis by 20%
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])
2) For the labeling, I am using the ax1.legend((p1, p2, p3), ("label for p1", "label for p2", "label for p3")) procedure.
If I ran the code with plt.show() and sys.exit() commented, the entire graph is produced:
However when implementing the inset answer, and trying to inset to the area of the pink and blue data:
(1) Replace plt.figure() by fig, ax1 = plt.subplots(),
(2) Using a ax2 for the inset, since a ax1 has already been used for placing the legend outside the graph,
(3) Uncommentplt.show() and sys.exit(),
no data is plotted both in the parent and inset graphs:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import sys
x_1 = np.array([ 2.56480648, 2.56635664, 2.57565757, 2.59425943, 2.61906191, 2.64463946,
2.66711671, 2.69966997, 2.72292229, 2.75392539, 2.79422942, 2.81360636,
2.84460946, 2.88026303, 2.91746675, 2.94846985, 2.99187419, 3.01822682,
3.06085609, 3.08565857, 3.12286229, 3.18331833, 3.24067407, 3.25772577,
3.36158616, 3.35616062, 3.43056806, 3.45847085, 3.61574815, 3.65387259,
3.89764927, 9.1 ])
x_2 = np.array([ 5.77982798, 5.77827783, 5.79067907, 5.81083108, 5.82788279, 5.85113511,
5.87438744, 5.89763976, 5.92011701, 5.94414441, 5.96584658, 5.98987399,
6.01467647, 6.03637864, 6.06118112, 6.08443344, 6.11543654, 6.13248825,
6.16194119, 6.18751875, 6.21077108, 6.23479848, 6.26192619, 6.29137914,
6.32083208, 6.35028503, 6.38128813, 6.41306631, 6.45569557, 6.47894789,
6.50530053, 6.55645565, 6.5959846 , 6.62853785, 6.67349235, 6.71612161,
6.76417642, 6.80293029, 6.86726173, 6.91841684, 6.96182118, 7.04165417,
7.10908591, 7.23774877, 7.30208021, 9.40021502])
y_1 = np.array([ 0., 10., 30.1, 50.2, 70.3, 90.4, 110.51, 130.61, 150.71,
170.81, 190.91, 211.01, 231.11, 251.21, 271.31, 291.41, 311.52, 331.62,
351.72, 371.82, 391.92, 412.02, 432.12, 452.22, 472.32, 492.42, 512.53,
532.63, 552.73, 572.83, 592.93, 592.93])
y_2 = np.array([ 0., 10., 30.1, 50.2, 70.3, 90.4, 110.51, 130.61, 150.71,
170.81, 190.91, 211.01, 231.11, 251.21, 271.31, 291.41, 311.52, 331.62,
351.72, 371.82, 391.92, 412.02, 432.12, 452.22, 472.32, 492.42, 512.53,
532.63, 552.73, 572.83, 592.93, 613.03, 633.13, 653.23, 673.33, 693.43,
713.54, 733.64, 753.74, 773.84, 793.94, 814.04, 834.14, 854.24, 874.34,
894.44])
x_3 = np.array([ 273.15, 323.15, 373.15, 423.15, 473.15])
x_4 = np.array([ 295.16725084, 378.53216084, 476.23703528, 490.56204235])
y_3 = np.array([ 1.4709975, 1.42196425, 1.372931 , 1.32389775, 1.2748645 ])
y_4 = np.array([ 1.43766266, 1.46267139, 1.51159861, 1.52367087])
### Plotting:
plt.figure()
#fig, ax1 = plt.subplots()
p1 = plt.scatter(x_1, y_1, color='red', marker='o', s=40)
p3 = plt.scatter(x_2, y_2, marker="o", color='black', facecolors='none', s=40)
p3c = plt.scatter(y_3, x_3, color='magenta', marker="o", facecolors='none', s=40)
p4 = plt.scatter(y_4, x_4, color='blue', marker='o', s=40)
fontP = FontProperties()
fontP.set_size('12')
ax1 = plt.subplot(111)
# Shrink current axis by 20% in order to allow the legend to be outside the plot:
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax1.legend((\
p1,\
p3,\
p3c,\
p4\
),\
(\
"1",\
"2",\
"3",\
"4"\
),\
prop=fontP, loc='center left', bbox_to_anchor=(1, 0.5))# loc=4)
extraticks=[273.15+25]
plt.yticks(list(plt.yticks()[0]) + extraticks)
plt.gca().set_xlim(right=8)
plt.gca().set_ylim(bottom=-41.72, top=1040)
plt.grid()
plt.show()
sys.exit()
left, bottom, width, height = [0.25, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])
p3 = ax2.scatter(x_2, y_2, color='black', marker="o", facecolors='none', s=40)
p3c = ax2.scatter(x_3, y_3, color='magenta', marker="o", facecolors='none', s=40)
ax2.set_xlim(right=2.26)
plt.gca().set_ylim(bottom=200, top=1040)
plt.grid()
plt.savefig('plot.pdf', bbox_inches='tight')
plt.show()
I think there are simply some useless commands all over the place which make the code produce 2 figures instead of one and several subplots instead of one. Also the limits of the inset seem to be off. Removing all of this would give you the following plot, which might be what you're after.
### Plotting:
fig, ax1 = plt.subplots()
p1 = plt.scatter(x_1, y_1, color='red', marker='o', s=40)
p3 = plt.scatter(x_2, y_2, marker="o", color='black', facecolors='none', s=40)
p3c = plt.scatter(y_3, x_3, color='magenta', marker="o", facecolors='none', s=40)
p4 = plt.scatter(y_4, x_4, color='blue', marker='o', s=40)
fontP = FontProperties()
fontP.set_size('12')
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax1.legend((p1,p3,p3c,p4),("1","2","3","4"),
prop=fontP, loc='center left', bbox_to_anchor=(1, 0.5))
extraticks=[273.15+25]
plt.yticks(list(plt.yticks()[0]) + extraticks)
plt.gca().set_xlim(right=8)
plt.gca().set_ylim(bottom=-41.72, top=1040)
plt.grid()
left, bottom, width, height = [0.25, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])
p3 = ax2.scatter(x_2, y_2, color='black', marker="o", facecolors='none', s=40)
p3c = ax2.scatter(x_3, y_3, color='magenta', marker="o", facecolors='none', s=40)
plt.grid()
plt.savefig('plot.pdf', bbox_inches='tight')
plt.show()

Categories

Resources