This question already has answers here:
How do I equalize the scales of the x-axis and y-axis?
(5 answers)
Closed 2 years ago.
I want to plot a circle on a grid in python. I just need python to show the grid with squared cells. I wrote the following code, but it shows the grid with NON-squared cells.
Can anyone tell me how to make the grid cells be squared ?
import matplotlib.pyplot as plt
import math
p=8
R=0.484*p
t=np.linspace(0, 2*np.pi)
x=R*np.cos(t)
y=R*np.sin(t)
plt.axis("equal")
plt.grid(True, which='both', axis='both')
plt.plot(x,y)
plt.show()
Remove plt.axis("equal") and instead set plt.gca().set_aspect('equal'), which precisely sets the ratio of y-unit to x-unit of the axis scaling:
plt.grid(True, which='both', axis='both')
plt.plot(x,y)
plt.gca().set_aspect("equal")
plt.show()
Which would be the same as setting plt.axis('square').
Note that as mentioned in the docs, plt.axis("equal") is equal to setting plt.gca().set_aspect('equal', adjustable='datalim'), which will not produce the expected output, since data limits may not be respected in this case.
The above will give:
If you add this line after plt.grid() it will write all the x-ticks and the squares will be squared:
plt.xticks(range(-6, 6))
Related
This question already has answers here:
Matplotlib Legends not working
(4 answers)
How to set the y-axis limit
(8 answers)
Closed 1 year ago.
I plotted PDF using kdeplot. I am having a tough time to scale and label the plots.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
error = np.array([1,2,2,3,4,4,5])
error2 = np.array([3,3,4,4,4,6])
sns.kdeplot(error, color='blue',label='error')
sns.kdeplot(error2, color='red',label='error2')
plt.show()
I want the blue curve to be labelled as 'error' and red curve to be labelled as 'error2'.
Also, I want to scale the y-axis. It should be in the range of 0 to 1 with 0.1 interval. How can I achieve this?
Thanks in advance
To add a legend, just add
plt.legend()
above plt.show(). To set the limit of the axis, use
ax = plt.gca() # get current axis
ax.set_ylim([0, 1])
To set the ticks accordingly, you can use
ax.set_yticks(np.arange(0, 1.1, 0.1))
(All above plt.show())
This question already has answers here:
Rotate tick labels in subplot (Pyplot, Matplotlib, gridspec)
(3 answers)
Closed 2 years ago.
I'm trying to plot a lot a data points and the X axis is timestamps. My problem is that for some length Matplotlib automatically squeezes them together and you cannot read the x axis, as shown in the pic:
How can I prevent this from happening? I'm trying to save that plot automatically with savefig(). It is saved to a PNG.
you can specify the X-Ticks with following:
import matplotlib.pyplot as plt
plt.plot(x_values, y_value)
plt.xticks([0,5,10])
The Plot will have less ticks.
WIthout the x-ticks:
With x-ticks:
I found the answer here on the matplotlib site:
https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html
fig, ax = plt.subplots()
ax.plot(date, r.close)
# rotate and align the tick labels so they look better
fig.autofmt_xdate()
# use a more precise date string for the x axis locations in the
# toolbar
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.set_title('fig.autofmt_xdate fixes the labels')
This question already has answers here:
How do I change the plot size of a regplot in Seaborn?
(2 answers)
Closed 4 years ago.
I've tried as many solutions as I could find on here, but I'm not having much luck on this. I'm not sure if it's because some of my settings, but I am unable to reshape my Seaborn countplot. Here's my code where I plot the figure:
sns.set_style('whitegrid')
sns.set(font_scale=1.3)
sns.countplot(x=df['QuarterYear'], hue=df['Modifier'])
ax = plt.gca()
for p in ax.patches:
ax.text(p.get_x() + p.get_width()/2., p.get_height(), '%d' % int(p.get_height()),
fontsize=12, color='black', ha='center', va='bottom')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
I am also editing the legend and labeling my countplot columns in the same block of code.
I am using Jupyter Notebook %inline. If anyone could explain what I am missing, that would be great. I've tried many, many variations of these solutions, to no avail.
How do I change the figure size for a seaborn plot?
How to make seaborn.heatmap larger (normal size)?
How do I change the plot size of a regplot in Seaborn?
Any help would be appreciated. Thank you for your time!
Have you tried:
fig = plt.gcf()
fig.set_size_inches( 16, 10)
This question already has answers here:
graphing multiple types of plots (line, scatter, bar etc) in the same window
(2 answers)
Python equivalent to 'hold on' in Matlab
(5 answers)
Closed 5 years ago.
I'm trying to plot scatter with over lined line plot. I have two sets of data and if I plot both of them as scatter plots it works, but if I try to plot the second one as a line graph (connected scatter plot), it won't even show.
plt.scatter(column1,column2,s=0.1,c='black')
plt.plot(column3,column4, marker='.', linestyle=':', color='r',)
(I tried using plt.scatter, I tried changing the markers and linestyle, tried without these as well and I still can't get it to work, I sometimes get the dots, but once I want them to be connected they disappear or nothing happens.)
plt.gca().invert_yaxis()
plt.show()
That's what I get:
Plot 1
matplotlib simply overlays plot commands in the called order as long as you do not create a new figure.
As an example, try this code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
N = 100
x = 0.9 * np.random.rand(N)
y = 0.9 * np.random.rand(N)
plt.scatter(x, y, c='green')
plt.plot(np.linspace(0, 1, 10), np.power(np.linspace(0, 1, 10), 2), c= "red", marker='.', linestyle=':')
plt.gca().invert_yaxis()
plt.show()
This question already has answers here:
How to show minor tick labels on log-scale with Matplotlib
(2 answers)
Closed 7 years ago.
Upon adding the line plt.yscale('log') to my simple plotting script
import numpy as np
residuals = np.loadtxt('res_jacobi.txt', skiprows=1)
import matplotlib.pyplot as plt
fig = plt.figure()
steps = np.arange(0, len(residuals), 1)
plt.plot(steps, residuals, label='$S$')
plt.xlabel("Step",fontsize=20)
plt.ylabel("$S$",fontsize=20)
plt.ylim(0.95 * min(residuals), 1.05 * max(residuals))
plt.yscale('log')
plt.savefig('jacobi-res.pdf', bbox_inches='tight', transparent=True)
the y labels disappear.
I'm sure there is simple fix for this but searching did not turn one up. Any help would be much appreciated.
The normal behavior for matplotlib is to only label major tick marks in log-scaling --- which are even orders of magnitude, e.g. {0.1, 1.0}. Your values are all between those. You can:
rescale your axes to larger bounds,
plt.gca().set_ylim(0.1, 1.0)
label the tick-marks manually,
plt.gca().yaxis.set_minor_formatter(FormatStrFormatter("%.2f"))
semilogy works for me.
Change:
plt.plot(steps, residuals, label='$S$')
Into:
plt.semilogy(steps, residuals, label='$S$')
Remove plt.yscale('log')