Here is a part of the plot that I have
I need to create TrendLine that would be extended to the 3th
quarter of this plot... I can's think of any solution.
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
x = [1, 8, 12, 20]
y = [1, 8.4, 12.5, 20]
fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot()
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 20)
plt.subplot().spines['left'].set_position('center')
plt.subplot().spines['bottom'].set_position('center')
plt.plot(x,y, 'b.', ms=20)
plt.minorticks_on()
ax.grid(True, which='both')
mean_line = ax.plot()
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")
plt.show()
I don't think reverse x and y would do the job, it would be limited to the poly1d that pass (0,0)
I think the extending method should be using the fitted line itself.
so a more general method is extend the x and use the poly1d(z) to calculate an extended line. z is description of the fitted line, so feeding x value to z would draw the line.
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings('ignore')
x = [1, 8, 12, 20]
y = [1, 8.4, 12.5, 20]
# make an xx that with from -20 to 20
#xx =np.array(x)
#xx = sorted(np.concatenate((-xx, xx), axis=0))
xx = [-20, 20] # also work
fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 20)
plt.subplot().spines['left'].set_position('center')
plt.subplot().spines['bottom'].set_position('center')
plt.subplot().spines['right'].set_color('none')
plt.subplot().spines['top'].set_color('none')
plt.plot(x,y, 'b.', ms=20)
plt.minorticks_on()
#ax.grid(True, which='both')
plt.subplot().grid(True, which='both')
mean_line = ax.plot()
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(xx,p(xx),"r--")
plt.show()
if you zoomin near the (0,0), you should see it's not passing the origin point.
zoomed in near (0,0)
result image
I don't have any experience with trendlines, but I created a composite of existing x and y values with different signs and drew the following graph.
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
x = [1, 8, 12, 20]
y = [1, 8.4, 12.5, 20]
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot()
ax.set_xlim(-30, 30)
ax.set_ylim(-20, 20)
plt.subplot().spines['left'].set_position('center')
plt.subplot().spines['bottom'].set_position('center')
plt.plot(x,y, 'b.', ms=20)
plt.minorticks_on()
ax.grid(True, which='both')
mean_line = ax.plot()
# update
xx =np.array(x)
xx = sorted(np.concatenate((-xx, xx), axis=0))
yy =np.array(y)
yy = sorted(np.concatenate((-yy, yy), axis=0))
z = np.polyfit(xx, yy, 1)
p = np.poly1d(z)
plt.plot(xx,p(xx),"r--")
plt.show()
Related
I have 9 temperature points. 1 in the center and 8 on the circle. I need to create a heatmap in a circle. I set the points at which to perform calculations, and use the scipy.interpolate.griddata, but the full circle is not drawn, program draws an octagon. How can i fill in the missing parts?
import scipy.interpolate
import numpy
import matplotlib
import matplotlib.pyplot as plt
import math
# close old plots
plt.close("all")
# some parameters
xy_center = [2,2] # center of the plot
radius = 2 # radius
# mostly original code
meanR = [33.9, 34.2, 33.1, 33.5, 33., 32.7, 32.3, 31.8, 35.]
x = numpy.array([2, 2, 2+math.sqrt(2), 4, 2+math.sqrt(2), 2, 2+(-math.sqrt(2)), 0, 2+(-math.sqrt(2))])
y = numpy.array([2, 4, 2+math.sqrt(2), 2, 2+(-math.sqrt(2)), 0, 2+(-math.sqrt(2)), 2, 2+math.sqrt(2)])
z = meanR
xi, yi = numpy.mgrid[x.min():x.max():500j, y.min():y.max():500j]
zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='cubic')
# make figure
fig = plt.figure(figsize=(10, 10))
# set aspect = 1 to make it a circle
ax = fig.add_subplot(111, aspect = 1)
# use different number of levels for the fill and the lines
CS = ax.contourf(xi, yi, zi, 300, cmap=plt.cm.viridis, zorder=1)
# make a color bar
cbar = fig.colorbar(CS, ax=ax)
# add the data points
ax.scatter(x, y, marker = 'o', c = 'b', s = 15, zorder = 3)
for i in range(9):
ax.annotate(str(z[i]), (x[i],y[i]))
# draw a circle
circle = matplotlib.patches.Circle(xy = xy_center, radius = radius, edgecolor = "k", facecolor = "none")
ax.add_patch(circle)
# remove the ticks
ax.set_xticks([])
ax.set_yticks([])
# set axes limits
ax.set_xlim(-0.5, 4.5)
ax.set_ylim(-0.5, 4.5)
plt.show()
Radial basis functions (Rbf) can be used to interpolate/extrapolate your data.
scipy.interpolation Here is a modified code that produces the plot you need.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import math
from scipy.interpolate import Rbf
# some parameters
xy_center = [2,2] # center of the plot
radius = 2 # radius
# Data part
# ---------
# mostly original code
meanR = [33.9, 34.2, 33.1, 33.5, 33., 32.7, 32.3, 31.8, 35.] #9 points data
x = np.array([2, 2, 2+math.sqrt(2), 4, 2+math.sqrt(2), 2, 2+(-math.sqrt(2)), 0, 2+(-math.sqrt(2))])
y = np.array([2, 4, 2+math.sqrt(2), 2, 2+(-math.sqrt(2)), 0, 2+(-math.sqrt(2)), 2, 2+math.sqrt(2)])
z = meanR
# use RBF (Radial basis functions) that allows extrapolation
rbf = Rbf(x, y, z, epsilon=radius+1) #epsilon is based on some parameters of the data
# Interpolation/extrapolation
# ---------------------------
xi, yi = np.mgrid[x.min():x.max():500j, y.min():y.max():500j]
# applies and get inter/extra-polated values
zi = rbf(xi, yi)
# make zi outside circle --> np.none
midr,midc = zi.shape[0]/2, zi.shape[1]/2
for er in range(zi.shape[0]):
for ec in range(zi.shape[1]):
if np.abs(math.sqrt((er-midr)**2 + (ec-midc)**2))>zi.shape[0]/2:
# outside the circle, dont plot this pixel
zi[er][ec] = np.nan
pass
pass
# make figure
fig = plt.figure(figsize=(8, 8))
# set aspect = 1 to make it a circle
ax = fig.add_subplot(111, aspect = 1)
# add the data points
ax.scatter(x, y, marker = 'o', c = 'b', s = 15, zorder = 3)
for i in range(9):
ax.annotate(str(z[i]), (x[i],y[i]))
# draw a circle
circle = matplotlib.patches.Circle(xy = xy_center, radius = radius, edgecolor = "k", facecolor = "none")
ax.add_patch(circle)
CS = ax.contourf(xi, yi, zi, 300, cmap=plt.cm.viridis, zorder=1)
cbar = fig.colorbar(CS, ax=ax, shrink=0.7) # make a color bar
# remove the ticks
ax.set_xticks([])
ax.set_yticks([])
# set axes limits
ax.set_xlim(-0.5, 4.5)
ax.set_ylim(-0.5, 4.5)
plt.show()
The result:
I tried to plot error bar with Matplotlib like graphic attached, I can't made it, any suggestion?
import numpy as np
import matplotlib.pyplot as plt
Media = data["Media"]
Periodo = data["Periodo"]
P10th = data["P10th"]
P90th = data["P90th"]
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
ax.errorbar(Media, P90th, P10th, color='red', ls='--', marker='o', capsize=5, capthick=1, ecolor='black')
plt.xticks(ind, ('1910-1940', '1950-1990', '1990-2000', '2001-2010') )
ax.set_ylim(ylims)
, please can you help me.
This is my output
Here's the plot for your data:
p_10 = [.19,.62, .77, 1]
p_90 = [7.19, 6.67, 7.36, 8.25]
M = [1.16, 2.06, 2.17, 2.52]
fig = plt.figure()
x = [1, 2, 3, 4]
y = M
yerr = [p_10, # 'down' error
p_90] # 'up' error
plt.errorbar(x, y, yerr=yerr, capsize=3, fmt="r--o", ecolor = "black")
I am trying to combine two colourmap legends in one. Colour values are defined from third (z) data.
I am trying plot one legend colormap with two color scheme.
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_excel('C:\\Users\user1\\PycharmProjects\\untitled\\Python_test.xlsx')
x = df['Vp_dry']
y = df['Vs_dry']
q = df['Vp_wet']
w = df['Vs_wet']
fig, ax = plt.subplots()
popt, pcov = curve_fit(lambda fx, a, b: a * fx ** -b, x, y)
x_linspace = np.linspace(min(x - 100), max(x + 100), 100)
power_y = popt[0]*x_linspace ** -popt[1]
ax1 = plt.scatter(x, y, c=df['Porosity'], cmap=plt.cm.Greys, vmin=2, vmax=df['Porosity'].max(), edgecolors="#B6BBBD")
plt.plot(x_linspace, power_y, color='grey', label='Dry')
popt, pcov = curve_fit(lambda fx, a, b: a * fx ** -b, q, w)
q_linspace = np.linspace(min(q - 100), max(q + 100), 100)
power_w = popt[0]*q_linspace ** -popt[1]
ax2 = plt.scatter(q, w, c=df['Porosity'], cmap=plt.cm.Blues, vmin=2, vmax=df['Porosity'].max(), edgecolors="#3D83C1")
plt.plot(q_linspace, power_w, label='Wet')
cbar = fig.colorbar(ax2)
cbar = fig.colorbar(ax1)
cbar.set_label("Porosity (%)")
plt.xlabel('Vp (m/s)')
plt.ylabel('Vs (m/s)')
plt.grid()
plt.legend()
plt.show()
Desired result:
You seem to need a colorbar with two color maps combined, one of them reversed, and have the ticks changed to percentage values.
An approach is to manually create a second subplot, use two images and make it look like a colorbar:
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
# first create some dummy data to plot
N = 100
x = np.random.uniform(0, 10, N)
y = np.random.normal(15, 2, N)
q = np.random.uniform(0, 10, N)
w = np.random.normal(10, 2, N)
df_porosity = np.random.uniform(0, 5, N)
fig, (ax, ax2) = plt.subplots(ncols=2, figsize=(6, 4), gridspec_kw={"width_ratios": [1, 0.08]})
plot1 = ax.scatter(x, y, c=df_porosity, cmap=plt.cm.Greys, vmin=2, vmax=df_porosity.max(), edgecolors="#B6BBBD")
plot2 = ax.scatter(q, w, c=df_porosity, cmap=plt.cm.Blues, vmin=2, vmax=df_porosity.max(), edgecolors="#3D83C1")
img_cbar = np.linspace(0, 1, 256).reshape(256, 1)
ax2.imshow(img_cbar, cmap=plt.cm.Blues, extent=[0, 1, 1, 0]) # aspect='auto')
ax2.imshow(img_cbar, cmap=plt.cm.Greys, extent=[0, 1, -1, 0])
ax2.set_ylim(-1, 1)
ax2.set_aspect(10)
ax2.set_ylabel("Porosity (%)")
ax2.yaxis.set_label_position("right")
ax2.set_xticks([])
ax2.yaxis.tick_right()
# optionally show the ticks as percentage, where 1.0 corresponds to 100 %
ax2.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
plt.tight_layout()
plt.show()
Here is a simple plot:
1) How to disable the ticks?
2) How to reduce their number?
Here is a sample code:
from pylab import *
import numpy as np
x = [5e-05, 5e-06, 5e-07, 5e-08, 5e-09, 5e-10]
y = [-13, 14, 100, 120, 105, 93]
def myfunc(x,p):
sl,yt,yb,ec=p
y = yb + (yt-yb)/(1+np.power(10, sl*(np.log10(x)-np.log10(ec))))
return y
xp = np.power(10, np.linspace(np.log10(min(x)/10), np.log10(max(x)*10), 100))
pxp=myfunc(xp, [1,100,0,1e-6])
subplot(111,axisbg="#dfdfdf")
plt.plot(x, y, '.', xp, pxp, 'g-', linewidth=1)
plt.xscale('log')
plt.grid(True,ls="-", linewidth=0.4, color="#ffffff", alpha=0.5)
plt.draw()
plt.show()
Which produces:
plt.minorticks_off()
Turns em off!
To change the number of them/position them, you can use the subsx parameter. like this:
plt.xscale('log', subsx=[2, 3, 4, 5, 6, 7, 8, 9])
From the docs:
subsx/subsy: Where to place the subticks between each major tick.
Should be a sequence of integers. For example, in a log10 scale: [2,
3, 4, 5, 6, 7, 8, 9]
will place 8 logarithmically spaced minor ticks between each major
tick.
Calling plt.minorticks_off() will apply this to the current axis. (The function is actually a wrapper to gca().minorticks_off().)
You can also apply this to an individual axis in the same way:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.minorticks_off()
from pylab import *
import numpy as np
x = [5e-05, 5e-06, 5e-07, 5e-08, 5e-09, 5e-10]
y = [-13, 14, 100, 120, 105, 93]
def myfunc(x,p):
sl,yt,yb,ec=p
y = yb + (yt-yb)/(1+np.power(10, sl*(np.log10(x)-np.log10(ec))))
return y
xp = np.power(10, np.linspace(np.log10(min(x)/10), np.log10(max(x)*10), 100))
pxp=myfunc(xp, [1,100,0,1e-6])
ax=subplot(111,axisbg="#dfdfdf")
plt.plot(x, y, '.', xp, pxp, 'g-', linewidth=1)
plt.xscale('log')
plt.grid(True,ls="-", linewidth=0.4, color="#ffffff", alpha=0.5)
plt.minorticks_off() # turns off minor ticks
plt.draw()
plt.show()
Consider this y(x) function:
where we can generate these scattered points in a file: dataset_1D.dat:
# x y
0 0
1 1
2 0
3 -9
4 -32
The following is a 1D interpolation code for these points:
Load this scattered points
Create a x_mesh
Perform a 1D interpolation
Code:
import numpy as np
from scipy.interpolate import interp2d, interp1d, interpnd
import matplotlib.pyplot as plt
# Load the data:
x, y = np.loadtxt('./dataset_1D.dat', skiprows = 1).T
# Create the function Y_inter for interpolation:
Y_inter = interp1d(x,y)
# Create the x_mesh:
x_mesh = np.linspace(0, 4, num=10)
print x_mesh
# We calculate the y-interpolated of this x_mesh :
Y_interpolated = Y_inter(x_mesh)
print Y_interpolated
# plot:
plt.plot(x_mesh, Y_interpolated, "k+")
plt.plot(x, y, 'ro')
plt.legend(['Linear 1D interpolation', 'data'], loc='lower left', prop={'size':12})
plt.xlim(-0.1, 4.2)
plt.grid()
plt.ylabel('y')
plt.xlabel('x')
plt.show()
This plots the following:
Now, consider this z(x,y) function:
where we can generate these scattered points in a file: dataset_2D.dat :
# x y z
0 0 0
1 1 0
2 2 -4
3 3 -18
4 4 -48
In this case we would have to perform a 2D interpolation:
import numpy as np
from scipy.interpolate import interp1d, interp2d, interpnd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Load the data:
x, y, z = np.loadtxt('./dataset_2D.dat', skiprows = 1).T
# Create the function Z_inter for interpolation:
Z_inter = interp2d(x, y, z)
# Create the x_mesh and y_mesh :
x_mesh = np.linspace(1.0, 4, num=10)
y_mesh = np.linspace(1.0, 4, num=10)
print x_mesh
print y_mesh
# We calculate the z-interpolated of this x_mesh and y_mesh :
Z_interpolated = Z_inter(x_mesh, y_mesh)
print Z_interpolated
print type(Z_interpolated)
print Z_interpolated.shape
# plot:
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left', prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
This plots the following:
where the scattered data is shown again in red dots, to be consistent with the 2D plot.
I do not know how to interpret the Z_interpolated result:
According to the printing lines for the above code,
Z_interpolated is a n-dimensional numpy array, of shape (10,10). In other words, a 2D matrix with 10 rows and 10 columns.
I would have expected an interpolated z[i] value for each value of x_mesh[i] and y_mesh[i] Why I do not receive this ?
How could I plot also in the 3D plot the interpolated data (just like the black crosses in the 2D plot)?
Interpretation of Z_interpolated: your 1-D x_mesh and y_mesh defines a mesh on which to interpolate. Your 2-D interpolation return z is therefore a 2D array with shape (len(y), len(x)) which matches np.meshgrid(x_mesh, y_mesh). As you can see, your z[i, i], instead of z[i], is the expected value for x_mesh[i] and y_mesh[i]. And it just has a lot more, all values on the mesh.
A potential plot to show all interpolated data:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp2d
# Your original function
x = y = np.arange(0, 5, 0.1)
xx, yy = np.meshgrid(x, y)
zz = 2 * (xx ** 2) - (xx ** 3) - (yy ** 2)
# Your scattered points
x = y = np.arange(0, 5)
z = [0, 0, -4, -18, -48]
# Your interpolation
Z_inter = interp2d(x, y, z)
x_mesh = y_mesh = np.linspace(1.0, 4, num=10)
Z_interpolated = Z_inter(x_mesh, y_mesh)
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot your original function
ax.plot_surface(xx, yy, zz, color='b', alpha=0.5)
# Plot your initial scattered points
ax.scatter(x, y, z, color='r', marker='o')
# Plot your interpolation data
X_real_mesh, Y_real_mesh = np.meshgrid(x_mesh, y_mesh)
ax.scatter(X_real_mesh, Y_real_mesh, Z_interpolated, color='g', marker='^')
plt.show()
You would need two steps of interpolation. The first interpolates between y data. And the second interpolates between z data. You then plot the x_mesh with the two interpolated arrays.
x_mesh = np.linspace(0, 4, num=16)
yinterp = np.interp(x_mesh, x, y)
zinterp = np.interp(x_mesh, x, z)
ax.scatter(x_mesh, yinterp, zinterp, c='k', marker='s')
In the complete example below I added some variation in y direction as well to make the solution more general.
u = u"""# x y z
0 0 0
1 3 0
2 9 -4
3 16 -18
4 32 -48"""
import io
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Load the data:
x, y, z = np.loadtxt(io.StringIO(u), skiprows = 1, unpack=True)
x_mesh = np.linspace(0, 4, num=16)
yinterp = np.interp(x_mesh, x, y)
zinterp = np.interp(x_mesh, x, z)
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_mesh, yinterp, zinterp, c='k', marker='s')
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left', prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
For using scipy.interpolate.interp1d the solution is essentially the same:
u = u"""# x y z
0 0 0
1 3 0
2 9 -4
3 16 -18
4 32 -48"""
import io
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Load the data:
x, y, z = np.loadtxt(io.StringIO(u), skiprows = 1, unpack=True)
x_mesh = np.linspace(0, 4, num=16)
fy = interp1d(x, y, kind='cubic')
fz = interp1d(x, z, kind='cubic')
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_mesh, fy(x_mesh), fz(x_mesh), c='k', marker='s')
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left', prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()