I want to hide the x,y axes values as highlighted in the figure. Is it possible to do it? I also attach the expected representation.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
n=3
X = np.arange(n)
Y = -X
x_sorted = np.sort(X)
y_sorted = np.sort(Y)
ax.set_xticks(x_sorted)
ax.set_yticks(y_sorted)
ax.set_xlim(x_sorted[0], x_sorted[-1])
ax.set_ylim(y_sorted[0], y_sorted[-1])
ax.grid()
ax.set_aspect('equal', 'box')
plt.show()
The expected representation is
You need to empty x and y tick labels from ax variable:
ax.set_yticklabels([])
ax.set_xticklabels([])
Related
I want to create a scatter plot of (x,y) values where the x axis limits are [0, 10] and the y-axis limits are [0, 250]. The outer shape of the plot is supposed to be square, so the unit length of both axis has to be different.
I have tried both ax.axis('square') and ax.axis('equal') , before and after setting the axis limits (set by ax.set_xbound() and ax.set_ybound()) but none of these combinations produces my desired outcome.
x = np.random.randint(0,10,100)
y = np.random.randint(0,250,100)
fig, ax = plt.subplots()
ax.scatter(x,y)
ax.set_xbound(0,10)
ax.set_ybound(0,250)
ax.axis('square')
plt.show()
Outcome with ax.axis('square'):
The shape of the plot is square but now the x and y limits are both [0,250]
Use axes.set_box_aspect if you have reasonably recent matplotlib:
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_box_aspect.html
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randint(0,10,100)
y = np.random.randint(0,250,100)
fig, ax = plt.subplots()
ax.scatter(x,y)
ax.set_xbound(0,10)
ax.set_ybound(0,250)
ax.set_box_aspect(1)
plt.show()
I wonder how to set the size of the subplot when figure contains multiple subplots (5 × 2 in my case). No matter how big I allow the whole figure to be, the subplots always seem to be small. I would like to have direct control of the size of the subplot in this figure. The simplified version of the code is pasted below.
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(20)
y = np.random.randn(20)
fig = plt.figure(figsize=(20, 8))
for i in range(0,10):
ax = fig.add_subplot(5, 2, i+1)
plt.plot(x, y, 'o')
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
# x and y axis should be equal length
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.set_aspect(abs(x1-x0)/abs(y1-y0))
plt.show()
fig.savefig('plot.pdf', bbox_inches='tight')
Just switch figure size width and height from:
fig = plt.figure(figsize=(20, 8))
to:
fig = plt.figure(figsize=(8, 20))
to use the whole page for your plots.
This will change your plot from:
to:
Let suppose I have a matplotlib's gridspec instance in a python script. What I want to do is to create two axis and have the plot in one axis and the legend in the other one. Something like
import numpy as np
from matplotlib import gridspec, pyplot as plt
x = np.linspace(0,100)
y = np.sin(x)
gs = gridspec.GridSpec( 100, 100 )
ax1 = fig.add_subplot(gs[ :50, : ])
ax2 = fig.add_subplot(gs[ 55:, : ])
ax1.plot( s, y, label=r'sine' )
ax2.legend() # ?? Here I want legend of ax1
plt.show()
Is there any way of doing that?
You can grab the legend handles and labels from the first subplot using ax1.get_legend_handles_labels(), and then use them when you create the legend on the second subplot.
From the docs:
get_legend_handles_labels(legend_handler_map=None)
Return handles and labels for legend
ax.legend() is equivalent to:
h, l = ax.get_legend_handles_labels()
ax.legend(h, l)
import numpy as np
from matplotlib import gridspec, pyplot as plt
x = np.linspace(0, 100)
y = np.sin(x)
fig = plt.figure()
gs = gridspec.GridSpec(100, 100 )
ax1 = fig.add_subplot(gs[:50, :])
ax2 = fig.add_subplot(gs[55:, :])
ax1.plot(x, y, label=r'sine')
h, l = ax1.get_legend_handles_labels() # get labels and handles from ax1
ax2.legend(h, l) # use them to make legend on ax2
plt.show()
I'd like to change the size of the base and exponent to match the fontsize of the ticks on my colorbar. How can I do this?
for i in xrange(col):
plt.plot( t, x[i], color = s_m.to_rgba(slopes[i]), linewidth = 3 )
cbar = plt.colorbar(s_m)
cbar.formatter.set_powerlimits((0, 0))
cbar.update_ticks()
cbar.ax.tick_params(labelsize=20)
First off, let's cobble together a stand-alone example to demonstrate your problem. You've changed the size of the colorbar's tick labels, but the offset label didn't update. For example, it would be nice if the text at the top of the colorbar matched the size of the tick labels:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10, 10)) * 1e-6
fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=20)
ax.set(xticks=[], yticks=[])
plt.show()
What you're wanting to change is referred to as the offset_text. In this case, it's the offset text of the y-axis of the colorbar. You'd want to do something similar to:
cbar.ax.yaxis.get_offset_text.set(size=20)
or
cbar.ax.yaxis.offsetText.set(size=20)
As a complete example:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10, 10)) * 1e-6
fig, ax = plt.subplots()
im = ax.imshow(data)
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=20)
ax.set(xticks=[], yticks=[])
cbar.ax.yaxis.get_offset_text().set(size=20)
plt.show()
I have a very simple question. I need to have a second x-axis on my plot and I want that this axis has a certain number of tics that correspond to certain position of the first axis.
Let's try with an example. Here I am plotting the dark matter mass as a function of the expansion factor, defined as 1/(1+z), that ranges from 0 to 1.
semilogy(1/(1+z),mass_acc_massive,'-',label='DM')
xlim(0,1)
ylim(1e8,5e12)
I would like to have another x-axis, on the top of my plot, showing the corresponding z for some values of the expansion factor. Is that possible? If yes, how can I have xtics ax
I'm taking a cue from the comments in #Dhara's answer, it sounds like you want to set a list of new_tick_locations by a function from the old x-axis to the new x-axis. The tick_function below takes in a numpy array of points, maps them to a new value and formats them:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
X = np.linspace(0,1,1000)
Y = np.cos(X*20)
ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")
new_tick_locations = np.array([.2, .5, .9])
def tick_function(X):
V = 1/(1+X)
return ["%.3f" % z for z in V]
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()
You can use twiny to create 2 x-axis scales. For Example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)
ax2.plot(range(100), np.ones(100)) # Create a dummy plot
ax2.cla()
plt.show()
Ref: http://matplotlib.sourceforge.net/faq/howto_faq.html#multiple-y-axis-scales
Output:
From matplotlib 3.1 onwards you may use ax.secondary_xaxis
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000
# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1
fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')
ax2 = ax.secondary_xaxis("top", functions=(f,g))
ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()
If You want your upper axis to be a function of the lower axis tick-values you can do as below. Please note: sometimes get_xticks() will have a ticks outside of the visible range, which you have to allow for when converting.
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1 = fig.add_subplot(111)
ax1.plot(range(5), range(5))
ax1.grid(True)
ax2 = ax1.twiny()
ax2.set_xticks( ax1.get_xticks() )
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels([x * 2 for x in ax1.get_xticks()])
title = ax1.set_title("Upper x-axis ticks are lower x-axis ticks doubled!")
title.set_y(1.1)
fig.subplots_adjust(top=0.85)
fig.savefig("1.png")
Gives:
Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?"
Yes, it is.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)
ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])
plt.show()
You'll get:
I'm forced to post this as an answer instead of a comment due to low reputation.
I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:
ax2.lines = []
instead of using:
ax2.cla()
When in use also cleared my plot from ax1.