Create plot in matplotlib with appropriately sized axis - python

In the figure below, x-axis goes upto 54 and y-axis upto 8. However, the size of both is same. I would like to make the figure proportionate. I.e. x-axis should be longer than y-axis by a ratio of 54/8. Any suggestions?
fig = plt.figure()
plt.xlim(0,54)
plt.ylim(0,8)
#plt.axis('off')
plt.show()
plt.close()

Just add the following line:
fig = plt.figure()
plt.xlim(0,54)
plt.ylim(0,8)
plt.axes().set_aspect('equal')
plt.show()

Related

fixing the y scale in python matplotlib

I want to draw multiple bar plots with the same y-scale, and so I need the y-scale to be consistent.
For this, I tried using ylim() after yscale()
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
However, python keeps autoscaling the intermittent values depending on my data.
Is there a way to fix this?
overlayed graphs
import numpy as np
import matplotlib.pyplot as plt
xaxis = np.arange(10)
yaxis = np.random.rand(10)*100
fig = plt.subplots(figsize =(10, 7))
plt.bar(xaxis, yaxis, width=0.8, align='center', color='y')
# show graph
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
You can set the y-axis tick labels manually. See yticks for an example. In your case, you will have to do this for each plot to have consistent axes.

How to set X and Y intervals for matplotlib.pypplot.scatter()?

I have the following code for plotting two variables 'field_size' and 'field_mean_LAI':
plt.figure(figsize=(20,10))
plt.scatter(df.field_size, df.field_lai_mean)
plt.title("Field Size and LAI Plot")
plt.xlabel("Field Size")
plt.ylabel("Mean LAI")
plt.show()
The outcome is a scatter plot:
"
How can I configure the x and y intervals and change color of the plot?? I am very beginner in python plotting.
So I modified my code like below:
plt.figure(figsize=(20,10))
plt.scatter(df.field_size, df.field_lai_mean)
plt.title("Field Size and LAI Plot")
plt.xlabel("Field Size")
plt.ylabel("Mean LAI")
plt.xticks(np.arange(0.00000,0.00013,step=0.000008))
plt.yticks(np.arange(0,8.5,step=0.5))
plt.show()
Now I have a plot like this:
Just defined the xticks and yticks functions and it is done smoothly! :)
To change the color of plot points, you can use color attribute (see below).
To set limits of both axes, you can pass xlim and ylim parameters
while creating the subplot.
Note also that I passed here also rot parameter, to set x labels rotation.
And to configure x and y intervals, you can use e.g. MultipleLocator,
for both major and minor ticks. There are other locators too,
search the Web for details.
Additional element which you can set is also the grid (like I did).
So you can change your code to:
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig = plt.figure(figsize=(10,5))
ax = plt.subplot(xlim=(-0.000003, 0.000123), ylim=(-0.5, 9))
df.plot.scatter(x='field_size', y='field_lai_mean', rot=30, color='r', ax=ax)
plt.title("Field Size and LAI Plot")
plt.xlabel("Field Size")
plt.ylabel("Mean LAI")
ax = plt.gca()
ax.yaxis.set_major_locator(tck.MultipleLocator(2))
ax.yaxis.set_minor_locator(tck.MultipleLocator(0.4))
ax.xaxis.set_major_locator(tck.MultipleLocator(0.00001))
ax.xaxis.set_minor_locator(tck.MultipleLocator(0.0000025))
ax.grid()
plt.show()
Of course, adjust passed values to your needs.
For a very limited set of points, I got the following picture:

How to set equal number of ticks for two subplots?

I have two subplots of horizontal bars done in matplotlib. For the first subplot, the number of y-axis ticks is appropriate, but I'm unable to figure out why specifying number of ticks for the second subplot is coming out to be wrong. This is the code:
import matplotlib.pyplot as plt
import numpy as np
# Plot separate subplots for genders
fig, (axes1, axes2) = plt.subplots(nrows=1, ncols=2,
sharex=False,
sharey=False,
figsize=(15,10))
labels = list(out.index)
x = ["20%", "40%", "60%", "80%", "100%"]
y = np.arange(len(out))
width = 0.5
axes1.barh(y, female_distr, width, color="olive",
align="center", alpha=0.8)
axes1.ticks_params(nbins=6)
axes1.set_yticks(y)
axes1.set_yticklabels(labels)
axes1.set_xticklabels(x)
axes1.yaxis.grid(False)
axes1.set_xlabel("Occurence (%)")
axes1.set_ylabel("Language")
axes1.set_title("Language Distribution (Women)")
axes2.barh(y, male_distr, width, color="chocolate",
align="center", alpha=0.8)
axes2.locator_params(nbins=6)
axes2.set_yticks(y)
axes2.set_yticklabels(labels)
axes2.set_xticklabels(x)
axes2.yaxis.grid(False)
axes2.set_xlabel("Occurence (%)")
axes2.set_ylabel("Language")
axes2.set_title("Language Distribution (Men)")
The rest of the objects like out are simple data frames that I don't think need to be described here. The above code returns the following plot:
I would like the second subplot to have equal number of ticks but experimenting with nbins always results in either more or fewer ticks than the first subplot.
First, if you want your two plots to have the same x-axis, why not use sharex=True?
x_ticks = [0,20,40,60,80,100]
fig, (ax1,ax2) = plt.subplots(1,2, sharex=True)
ax1.set_xticks(x_ticks)
ax1.set_xticklabels(['{:.0f}%'.format(x) for x in x_ticks])
ax1.set_xlim(0,100)
ax1.grid(True, axis='x')
ax2.grid(True, axis='x')

Plotting multiple series on a line/bar graph with pandas

I'm trying to make a plot of a line and bar on the same graph. I'm close, but I can't solve a few items. Here's what I have so far...
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.DataFrame({'Value1': np.arange(80, 180, 1),
'Value2': np.arange(1.5, .5, -0.01)},
index=np.arange(10, 110, 1))
fig, ax = plt.subplots(figsize=(10, 10))
data['Value1'].plot(ax=ax)
ax2 = ax.twinx()
data['Value2'].plot(kind='bar', ax=ax2, color='y', ylim=(0, 3))
So the problems I have with this graph are...
The x-ticks look awful. If I only do a line graph, the x-ticks look fine. As soon as I add the twinx axis however, the major/minor ticks logic get's dropped. How can I keep that?
My x-axes is numeric. Note that the line intercepts the x-axis at the value "10" (its hard to see, but that's what's going on). I presume this is because the line's x-axis is supposed to begin at "10" and the bar's x-axis begins at 10 as well, but there's confusion of the value and label so the line's x-axis get's pushed over the label "20".
What's the best way to do this?
Bar plot and line plot has different X coordinate range is different, consider using two x coordinate.
you can try to save xticks and xtickslabels after data['Value1'].plot(ax=ax) and set them back after data['Value2'].plot(kind='bar', ax=ax2, color='y', ylim=(0, 3)):
data['Value1'].plot(ax=ax)
xticks = ax.get_xticks()
xlabels = [x.get_text() for x in ax.get_xticklabels()]
ax2 = ax.twinx()
data['Value2'].plot(kind='bar', ax=ax2, color='y', ylim=(0, 3))
ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
plt.show()

Set the plot y-axis and x-axis ratio equal

import numpy as np
import matplotlib.pyplot as plt
plt.figure(1)
plt.subplot(211)
xs = np.linspace(-5,5,500)
ys = np.sqrt(5**2 - xs**2)
plt.plot(xs,ys)
plt.plot(xs,-ys)
plt.subplot(212)
plt.plot(xs, xs**2)
plt.show()
here is the code i generate, was wondering that if i want keep the upper plot x and y ratio be 1:1 so that the ball will always look round no matter how many subplot inside this figure.
I tried to find it from the website, seems not a simple solution..
When you create your subplot, you can tell it:
plt.subplot(211, aspect='equal')
If you've already created the subplot, you have to grab the current axes, which you can do using plt.gca, then call the set_aspect method:
plt.gca().set_aspect('equal')
Or, you can keep track of the axes from the beginning:
ax = plt.subplot(211)
ax.set_aspect('equal')
You may have to call
plt.draw()
In order to update the plot.

Categories