Plotting with specific window in matplotlib - python-3.x

I'm trying to print the error ratio of the Hilbert matrix.
I'm trying to make the x axis 3 → 9 and the y axis rather for a large range:
8.71244799e+01 6.44297999e+02 4.50711567e+03 3.04673758e+04
2.01144882e+05 1.30525476e+06 8.35964228e+06
I'm struggling adjust the window, or plotting correctly for that.
Any help would be great!
Here is my attempt at plotting (something)
import matplotlib.pyplot as plt
plot = 6
plt.xlabel ('n')
plt.ylabel ('Error Ration')
fig = plt.figure()
ax = fig.add_subplot(111)
for a in range (0, plot, 1):
y = xratio[a]
x = plot + 3
ax.plot(x,y, mfc='orange', mec='orange', marker='.')
plt.show()

I think you just need to use:
ax.set_xlim([x_min, x_max])
ax.set_ylim([y_min, y_max])

Related

Top and right axes labels in matplotlib pyplot

I have a matplotlib/pyplot plot that appears as I want, in that the axes show the required range of values from -1 to +1 on both the x and y axes. I have labelled the x and y axes. However I also wish to label the right-hand vertical axis with the text "Thinking" and the top axis with the text "Extraversion".
I have looked at the matplotlib documentation but can't get my code to execute using set_xlabel and set_ylabel. I have commented these lines out in my code so my code runs for now - but hopefully the comments will make it clear enough what I am trying to do.
import matplotlib.pyplot as plt
w = 6
h = 6
d = 70
plt.figure(figsize=(w, h), dpi=d)
x = [-0.34,-0.155,0.845,0.66,-0.34]
y = [0.76,0.24,-0.265,0.735,0.76,]
plt.plot(x, y)
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("Intraverted")
plt.ylabel("Feeling")
#secax = plt.secondary_xaxis('top')
#secax.set_xlabel('Extraverted')
#secay = plt.secondary_xaxis('right')
#secay.set_ylabel('Thinking')
#plt.show()
plt.savefig("out.png")
As #Mr. T pointed out, there is no plt.secondary_xaxis method so you need the axes object
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6), constrained_layout=True, dpi=70)
x = [-0.34,-0.155,0.845,0.66,-0.34]
y = [0.76,0.24,-0.265,0.735,0.76,]
plt.plot(x, y)
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("Intraverted")
plt.ylabel("Feeling")
secax = plt.gca().secondary_xaxis('top')
secax.set_xlabel('Extraverted')
secay = plt.gca().secondary_yaxis('right')
secay.set_ylabel('Thinking')
#plt.show()
plt.savefig("out.png")
Better, would be just to create the axes object from the start:
fig, ax = plt.subplots(figsize=(w, h), constrained_layout=True, dpi=d)
...
ax.plot(x, y)
ax.set_xlim(-1, 1)
...
secax = ax.secondary_xaxis('top')
...
fig.savefig("out.png")
Further note the use of constrained_layout=True to make the secondary yaxis label fit on the figure.
i solved it with plt.subplots()
import matplotlib.pyplot as plt
w = 6
h = 6
d = 70
plt.figure(figsize=(w, h), dpi=d)
x = [-0.34,-0.155,0.845,0.66,-0.34]
y = [0.76,0.24,-0.265,0.735,0.76,]
fig , ax1 = plt.subplots()
ax1.plot(x, y)
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("Intraverted")
plt.ylabel("Feeling")
ax2 = ax1.twinx()
plt.ylabel('right corner')

Matplotlib - maintain plot size of uneven subplots

I've been creating uneven subplots in matplotlib based on this question. The gridspec solution (third answer) worked a little better for me as it gives a bit more flexibility for the exact sizes of the subplots.
When I add a plot of a 2D array with imshow() the affected subplot is resized to the shape of the array. Is there any way to avoid that and keep the subplot-sizes (or rather aspect-ratio) fixed?
Here's the example code and the resulting image with the subplot-sizes I'm happy with:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot
fig = plt.figure(figsize=(12, 9))
gs = gridspec.GridSpec(20, 20)
ax1 = fig.add_subplot(gs[0:5,0:11])
ax1.plot(x, y)
ax2 = fig.add_subplot(gs[6:11,0:11])
ax2.plot(y, x)
ax3 = fig.add_subplot(gs[12:20,0:11])
ax3.plot(y, x)
ax4 = fig.add_subplot(gs[0:9,13:20])
ax4.plot(x, y)
ax5 = fig.add_subplot(gs[11:20,13:20])
ax5.plot(y, x)
plt.show()
This is what happens if I additionally plot data from a 2D array with the following lines (insert before plt.show):
2Ddata = np.arange(0, 10, 0.1).reshape(10, 10)
im = ax3.imshow(2Ddata, cmap='rainbow')
How can I restore the original size of the subplot from ax3 (lower left corner)?
Including the line ax3.set_aspect('auto') seems to have solved the issue.

What kind of plot from matplotlib should I use?

I am programming in Python 3 and I have data structured like this:
coordinates = [(0.15,0.25),(0.35,0.25),(0.55,0.45),(0.65,0.10),(0.15,0.25)]
These are coordinates. Within each pair, the first number is the x coordinate and the second one the y coordinate. Some of the coordinates repeat themselves. I want to plot these data like this:
The coordinates that are most frequently found should appear either as higher intensity (i.e., brighter) points or as points with a different color (for example, red for very frequent coordinates and blue for very infrequent coordinates). Don't worry about the circle and semicircle. That's irrelevant. Is there a matplotlib plot that can do this? Scatter plots do not work because they do not report on the frequency with which each coordinate is found. They just create a cloud.
The answer is:
import matplotlib.pyplot as plt
from scipy.stats import kde
import numpy as np
xvalues = np.random.normal(loc=0.5,scale=0.01,size=50000)
yvalues = np.random.normal(loc=0.25,scale=0.1,size=50000)
nbins=300
k = kde.gaussian_kde([xvalues,yvalues])
xi, yi = np.mgrid[0:1:nbins*1j,0:1:nbins*1j]
zi = k(np.vstack([xi.flatten(),yi.flatten()]))
fig, ax = plt.subplots()
ax.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto', cmap=plt.cm.hot)
x = np.arange(0.0,1.01,0.01,dtype=np.float64)
y = np.sqrt((0.5*0.5)-((x-0.5)*(x-0.5)))
ax.axis([0,1,0,0.55])
ax.set_ylabel('S', fontsize=16)
ax.set_xlabel('G', fontsize=16)
ax.tick_params(labelsize=12, width=3)
ax.plot(x,y,'w--')
plt.show()

Matplotlib: How to copy a contour plot to another figure?

I have a figure with many different plots (contour plots and lots of other stuff). I want to extract the contour plot to another single figure to see more details. But I fail how to do so.
Have a look on this code:
import numpy as np
from matplotlib import gridspec as gs, pyplot as plt
# Figure 1 with many different plots.
fig1 = plt.figure()
gridSpec = gs.GridSpec(2, 3)
for i in range(6):
fig1.add_subplot(gridSpec[i])
# Create contour plot
x = np.arange(-3.0, 3.0, 0.02)
y = np.arange(-2.0, 2.0, 0.01)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) ** 4
# Plot it to a particular axes.
ax1 = fig1.axes[2]
contour = ax1.contour(X, Y, Z)
# Try to copy the contour plot to another figure (with only 1 subplot).
fig2, ax2 = plt.subplots()
# How to copy the content of ax1 to ax2?
plt.show()
This will give me the following:
I want to create a second figure with only 1 subplot and its content should be the same as you can see in top right corner of the first figure with 6 subplots.
First thing I tried was
ax2.add_collection(contour.collections[1])
but I got the error message
RuntimeError: Can not put single artist in more than one figure
This is because the content is already plottet to figure 1, so it is not possible to plot it to figure 2 as well. So I tried to make a copy of the contour plot:
from copy import deepcopy
ax2.add_collection(deepcopy(contour.collections[1]))
But this will get me a new error that copiing is not possible ...
NotImplementedError: TransformNode instances can not be copied. Consider using frozen() instead.
So .. what can I do? Any ideas for that problem? :)
Thanks a lot!
(Python 3.7.4, Matplotlib 3.1.1)

Add Color To 3D Scatter Plot

I have a list of x,y,z points and a list of values assigned to each 3D point.
Now the question is, how can I color each point in a 3D scatter plot according to the list of values ?
The colors should be typical engineering -> RGB -> lowest blue to highest red
Thanks a lot
Basically I am searching for an equivalent to: scatter3(X,Y,Z,S,C)
See here: https://ch.mathworks.com/help/matlab/ref/scatter3.html
I tried:
col = [i/max(values)*255 for i in values]
ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals,c=col, marker='o')
pyplot.show()
..but I don't get the desired result
Note the recommended way of producing scatters with colors is to supply the values directly to c:
ax.scatter(x, y, z, c=values, marker='o', cmap="Spectral")
Minimal example:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = y = z = values = [1,2,3,4,5]
ax = plt.subplot(projection="3d")
sc = ax.scatter(x, y, z, c=values, marker='o', s=100, cmap="Spectral")
plt.colorbar(sc)
plt.show()

Resources