How do I create a plot where the scales of x-axis and y-axis are the same?
This equal ratio should be maintained even if I change the window size. Currently, my graph scales together with the window size.
I tried:
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.axis('equal')
Use Axes.set_aspect in the following manner:
from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
ax = plt.gca()
ax.set_aspect('equal', adjustable='box')
plt.draw()
plt.axis('scaled')
works well for me.
See the documentation on plt.axis(). This:
plt.axis('equal')
doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:
plt.axis('square')
This creates a square plot with equal axes.
Try something like:
import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()
you can stretch the plot to square using this :
fig = plt.figure(figsize=(1, 1))
Related
Is there any way that I can divide an axis to a certain number of ticks and then label them? For example, I have the following plot and I want to have 4 ticks on the x axis and be able to set the labels myself.
and here's what I want to achieve (please note that the two plots are the same):
and this is the script I am using to create the plot:
import matplotlib.pyplot as plt
plt.imshow(data, cmap=plt.cm.jet)
plt.colorbar()
plt.show()
I can divide the axis using this: plt.locator_params(axis='x', nbins=4), but I could not set the labels myself.
As #ImportanceOfBeingErnest mentioned, using imshow's extent was the answer:
plt.imshow(data, extent=[0,1.5,3,0], cmap=plt.cm.jet)
I am trying to plot an image (using matplotlib.imshow) and a scatter plot within the same figure. When trying this, the image appears smaller than the scatter plot. Small example code is shown below:
import matplotlib.pyplot as plt
import numpy as np
image = np.random.randint(100,200,(200,200))
x = np.arange(0,10,0.1)
y = np.sin(x)
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(image)
ax2.scatter(x,y)
plt.show()
Which gives the following figure:
How can I get the two sublpots to have the same height? (and width I suppose)
I have tried using gridspec as shown in this answer:
fig=plt.figure()
gs=GridSpec(1,2)
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1])
ax1.imshow(image)
ax2.scatter(x,y)
But this gives the same result. I have also tried to adjust the subplot sizes manually by using:
fig = plt.figure()
ax1 = plt.axes([0.05,0.05,0.45,0.9])
ax2 = plt.axes([0.55,0.19,0.45,0.62])
ax1.imshow(image)
ax2.scatter(x,y)
By trial and error I can get the two subplots to the correct size, though any change in the overall figure size will mean that the subplots will no longer be the same size.
Is there a way to make imshow and a scatter plot appear the same size in a figure without manually changing the axes sizes?
I am using Python 2.7 and matplotlib 2.0.0
It's not perfectly clear what your desired outcome is.
You may use automatic aspect on the image
ax.imshow(z, aspect="auto")
Or you may set the aspect of the line plot depending on its axis limits such that it gets the same size as the image (in case the image has equal x and y sizes)
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
ax2.set_aspect(asp)
Complete code:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,20)
y = np.sin(x)
z = np.random.rand(100,100)
fig, (ax, ax2) = plt.subplots(ncols=2)
ax.imshow(z)
ax2.plot(x,y, marker=".")
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
ax2.set_aspect(asp)
plt.show()
If the image does not have equal limits (is not square), one still needs to divide by the aspect of the image:
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
asp /= np.abs(np.diff(ax1.get_xlim())[0] / np.diff(ax1.get_ylim())[0])
ax2.set_aspect(asp)
More sophisticated solutions:
This answer for using the subplot parameters to achieve a certain aspect.
If you want to use mpl_toolkits and make your hands dirty, this answer would be a good read.
I had the same problem and asked a very similar question in SO. The solution proposed by #ImportanceOfBeingErnest worked like a charm for me, but for completeness, I'd like to mention a pretty simple workaround I was suggested to apply (credit to #Yilun Zhang) before my question was marked as an exact duplicate of this one:
The problem is that the plot region height is too large and this is leaving empty place in the image.
If you change your code to:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
then you get the desired outcome:
Here's some code I use:
fig, axis_array = plt.subplots(1, 2, figsize=(chosen_value, 1.05 * chosen_value / 2),
subplot_kw={'aspect': 1})
I'm explicitly selecting that there will be 2 sub plots in my figure, and that the figure will be chosen_value tall and each subplot will be about half that size wide, and that the subplots will have an aspect ratio of 1 (i.e., they will both be square). The figure size is a specific ratio which forces the spacing.
For those sharing the y-axis across both plots, setting constrained_layout to True may help.
I am trying to plot an image (using matplotlib.imshow) and a scatter plot within the same figure. When trying this, the image appears smaller than the scatter plot. Small example code is shown below:
import matplotlib.pyplot as plt
import numpy as np
image = np.random.randint(100,200,(200,200))
x = np.arange(0,10,0.1)
y = np.sin(x)
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(image)
ax2.scatter(x,y)
plt.show()
Which gives the following figure:
How can I get the two sublpots to have the same height? (and width I suppose)
I have tried using gridspec as shown in this answer:
fig=plt.figure()
gs=GridSpec(1,2)
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1])
ax1.imshow(image)
ax2.scatter(x,y)
But this gives the same result. I have also tried to adjust the subplot sizes manually by using:
fig = plt.figure()
ax1 = plt.axes([0.05,0.05,0.45,0.9])
ax2 = plt.axes([0.55,0.19,0.45,0.62])
ax1.imshow(image)
ax2.scatter(x,y)
By trial and error I can get the two subplots to the correct size, though any change in the overall figure size will mean that the subplots will no longer be the same size.
Is there a way to make imshow and a scatter plot appear the same size in a figure without manually changing the axes sizes?
I am using Python 2.7 and matplotlib 2.0.0
It's not perfectly clear what your desired outcome is.
You may use automatic aspect on the image
ax.imshow(z, aspect="auto")
Or you may set the aspect of the line plot depending on its axis limits such that it gets the same size as the image (in case the image has equal x and y sizes)
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
ax2.set_aspect(asp)
Complete code:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,20)
y = np.sin(x)
z = np.random.rand(100,100)
fig, (ax, ax2) = plt.subplots(ncols=2)
ax.imshow(z)
ax2.plot(x,y, marker=".")
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
ax2.set_aspect(asp)
plt.show()
If the image does not have equal limits (is not square), one still needs to divide by the aspect of the image:
asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
asp /= np.abs(np.diff(ax1.get_xlim())[0] / np.diff(ax1.get_ylim())[0])
ax2.set_aspect(asp)
More sophisticated solutions:
This answer for using the subplot parameters to achieve a certain aspect.
If you want to use mpl_toolkits and make your hands dirty, this answer would be a good read.
I had the same problem and asked a very similar question in SO. The solution proposed by #ImportanceOfBeingErnest worked like a charm for me, but for completeness, I'd like to mention a pretty simple workaround I was suggested to apply (credit to #Yilun Zhang) before my question was marked as an exact duplicate of this one:
The problem is that the plot region height is too large and this is leaving empty place in the image.
If you change your code to:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
then you get the desired outcome:
Here's some code I use:
fig, axis_array = plt.subplots(1, 2, figsize=(chosen_value, 1.05 * chosen_value / 2),
subplot_kw={'aspect': 1})
I'm explicitly selecting that there will be 2 sub plots in my figure, and that the figure will be chosen_value tall and each subplot will be about half that size wide, and that the subplots will have an aspect ratio of 1 (i.e., they will both be square). The figure size is a specific ratio which forces the spacing.
For those sharing the y-axis across both plots, setting constrained_layout to True may help.
For the plot
sns.countplot(x="HostRamSize",data=df)
I got the following graph with x-axis label mixing together, how do I avoid this? Should I change the size of the graph to solve this problem?
Having a Series ds like this
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(136)
l = "1234567890123"
categories = [ l[i:i+5]+" - "+l[i+1:i+6] for i in range(6)]
x = np.random.choice(categories, size=1000,
p=np.diff(np.array([0,0.7,2.8,6.5,8.5,9.3,10])/10.))
ds = pd.Series({"Column" : x})
there are several options to make the axis labels more readable.
Change figure size
plt.figure(figsize=(8,4)) # this creates a figure 8 inch wide, 4 inch high
sns.countplot(x="Column", data=ds)
plt.show()
Rotate the ticklabels
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()
Decrease Fontsize
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)
plt.tight_layout()
plt.show()
Of course any combination of those would work equally well.
Setting rcParams
The figure size and the xlabel fontsize can be set globally using rcParams
plt.rcParams["figure.figsize"] = (8, 4)
plt.rcParams["xtick.labelsize"] = 7
This might be useful to put on top of a juypter notebook such that those settings apply for any figure generated within. Unfortunately rotating the xticklabels is not possible using rcParams.
I guess it's worth noting that the same strategies would naturally also apply for seaborn barplot, matplotlib bar plot or pandas.bar.
You can rotate the x_labels and increase their font size using the xticks methods of pandas.pyplot.
For Example:
import matplotlib.pyplot as plt
plt.figure(figsize=(10,5))
chart = sns.countplot(x="HostRamSize",data=df)
plt.xticks(
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='x-large'
)
For more such modifications you can refer this link:
Drawing from Data
If you just want to make sure xticks labels are not squeezed together, you can set a proper fig size and try fig.autofmt_xdate().
This function will automatically align and rotate the labels.
plt.figure(figsize=(15,10)) #adjust the size of plot
ax=sns.countplot(x=df['Location'],data=df,hue='label',palette='mako')
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") #it will rotate text on x axis
plt.tight_layout()
plt.show()
you can try this code & change size & rotation according to your need.
I don't know whether it is an option for you but maybe turning the graphic could be a solution (instead of plotting on x=, do it on y=), such that:
sns.countplot(y="HostRamSize",data=df)
In a matplotlib figure, how can I make the font size for the tick labels using ax1.set_xticklabels() smaller?
Further, how can one rotate it from horizontal to vertical?
There is a simpler way actually. I just found:
import matplotlib.pyplot as plt
# We prepare the plot
fig, ax = plt.subplots()
# We change the fontsize of minor ticks label
ax.tick_params(axis='both', which='major', labelsize=10)
ax.tick_params(axis='both', which='minor', labelsize=8)
This only answers to the size of label part of your question though.
To specify both font size and rotation at the same time, try this:
plt.xticks(fontsize=14, rotation=90)
Please note that newer versions of MPL have a shortcut for this task. An example is shown in the other answer to this question: https://stackoverflow.com/a/11386056/42346
The code below is for illustrative purposes and may not necessarily be optimized.
import matplotlib.pyplot as plt
import numpy as np
def xticklabels_example():
fig = plt.figure()
x = np.arange(20)
y1 = np.cos(x)
y2 = (x**2)
y3 = (x**3)
yn = (y1,y2,y3)
COLORS = ('b','g','k')
for i,y in enumerate(yn):
ax = fig.add_subplot(len(yn),1,i+1)
ax.plot(x, y, ls='solid', color=COLORS[i])
if i != len(yn) - 1:
# all but last
ax.set_xticklabels( () )
else:
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(14)
# specify integer or one of preset strings, e.g.
#tick.label.set_fontsize('x-small')
tick.label.set_rotation('vertical')
fig.suptitle('Matplotlib xticklabels Example')
plt.show()
if __name__ == '__main__':
xticklabels_example()
Alternatively, you can just do:
import matplotlib as mpl
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
Another alternative
I have two plots side by side and would like to adjust tick labels separately.
The above solutions were close however they were not working out for me. I found my solution from this matplotlib page.
ax.xaxis.set_tick_params(labelsize=20)
This did the trick and was straight to the point. For my use case, it was the plot on the right that needed to be adjusted. For the plot on the left since I was creating new tick labels I was able to adjust the font in the same process as seting the labels.
ie
ax1.set_xticklabels(ax1_x, fontsize=15)
ax1.set_yticklabels(ax1_y, fontsize=15)
thus I used for the right plot,
ax2.xaxis.set_tick_params(labelsize=24)
ax2.yaxis.set_tick_params(labelsize=24)
A minor subtlety... I know... but I hope this helps someone :)
Bonus points if anyone knows how to adjust the font size of the order of magnitude label.
plt.tick_params(axis='both', which='minor', labelsize=12)
In current versions of Matplotlib, you can do axis.set_xticklabels(labels, fontsize='small').
The following worked for me:
ax2.xaxis.set_tick_params(labelsize=7)
ax2.yaxis.set_tick_params(labelsize=7)
The advantage of the above is you do not need to provide the array of labels and works with any data on the axes.
For smaller font, I use
ax1.set_xticklabels(xticklabels, fontsize=7)
and it works!
You can also change label display parameters like fontsize with a line like this:
zed = [tick.label.set_fontsize(14) for tick in ax.yaxis.get_major_ticks()]