Matplotlib/pyplot: How to enforce axis range? - python

I would like to draw a standard 2D line graph with pylot, but force the axes' values to be between 0 and 600 on the x, and 10k and 20k on the y. Let me go with an example...
import pylab as p
p.title(save_file)
p.axis([0.0,600.0,1000000.0,2000000.0])
#define keys and items elsewhere..
p.plot(keys,items)
p.savefig(save_file, dpi=100)
However, the axes still adjust to the size of the data. I'm interpreting the effect of p.axis to be setting what the max and min could be, not enforcing them to be the max or min. The same happens when I try to use p.xlim() etc.
Any thoughts?
Thanks.

Calling p.plot after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim() or ylim() after your plot command.
I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with
lims = xlim()
xlim([lims[1], lims[0]])

To answer my own question, the trick is to turn auto scaling off...
p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show function and savefig function.
before you plot:
fig = pylab.figure()
ax = fig.gca()
ax.set_autoscale_on(False)
This is to request an ax which is subplot(1,1,1).
During the plot:
ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
After the plot:
To show the image :
fig.show()
To save the figure :
fig.savefig('the name of your figure')
I find out that put axis at the front of the code won't work even though I have set autoscale_on to False.
I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation.

Try putting the call to axis after all plotting commands.

Related

adjusting graph in maplotlib (python)

graph
how do I make this graph infill all the square around it? (I colored the part that I want to take off in yellow, for reference)
Normally I use two methods to adjust axis limits depending on a situation.
When a graph is simple, axis.set_ylim(bottom, top) method is a quick way to directly change y-axis (you might know this already).
Another way is to use matplotlib.ticker. It gives you more utilities to adjust axis ticks in your graph.
https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html
I'm guessing you're using a list of strings to set yaxis tick labels. You may want to set locations (float numbers) and labels (string) of y-axis ticks separatedly. Then set the limits on locations like the following snippet.
import matplotlib.pyplot as plt
import matplotlib.ticker as mt
fig, ax = plt.subplots(1,1)
ax.plot([0,1,2], [0,1,2])
ax.yaxis.set_major_locator(mt.FixedLocator([0,1,2]))
ax.yaxis.set_major_formatter(mt.FixedFormatter(["String1", "String2", "String3"]))
ax.set_ylim(bottom=0, top=2)
It gives you this: generated figure
Try setting the min and max of your x and y axes.

How set a specific range of x-axis and increase the length of the plot?

I´m looking to add a specific range of values to the x-axis of my plot and increase the length of this axis.
I change the range of the values of my x-axis; however, the values keep in a specific range.
Besides, I tried to increase the length of the x-axis but I failed again.
For now, I´m only plotting an empty graph, because a need to set the specifications for the axis.
Here is part of the code to the plot:
fig1, ax = plt.subplots()
ax.set_xlim(1, 1200)
ax.set_ylim(-800, 200)
ax.set_box_aspect(1)
plt.show()
This code gives me a plot square with the range of the:
x-axis = 0-200-400...1200,
I´m looking for:
x-axis = 0-50-100-150...1200
Also, I need to change the shape of the plot: square to a rectangular, where the x-axis increases the length.
Any suggestion or comment is welcome!
Thank!
plt.figure(figsize=(15,2))
Use this at first line to set the size of your plot. As you want to increase x-axis, then see that x>y in figsize parameter.
l1=np.arange(0,1250,50)
plt.xticks(l1)
Use the above code after setting y limits to set the xticks in range of 0-1200 with gap of 50.
``
You can change the size (and therefore the shape) of a pyplot figure like this:
fig1.set_size_inches(10, 8)
As for the ticks on the axis, this post gives a pretty in-depth answer on how to customize those.

Python, Seaborn: Logarithmic Swarmplot has unexpected gaps in the swarm

Let's look at a swarmplot, made with Python 3.5 and Seaborn on some data (which is stored in a pandas dataframe df with column lables stored in another class. This does not matter for now, just look at the plot):
ax = sns.swarmplot(x=self.dte.label_temperature, y=self.dte.label_current, hue=self.dte.label_voltage, data = df)
Now the data is more readable if plotted in log scale on the y-axis because it goes over some decades.
So let's change the scaling to logarithmic:
ax.set_yscale("log")
ax.set_ylim(bottom = 5*10**-10)
Well I have a problem with the gaps in the swarms. I guess they are there because they have been there when the plot is created with a linear axis in mind and the dots should not overlap there. But now they look kind of strange and there is enough space to from 4 equal looking swarms.
My question is: How can I force seaborn to recalculate the position of the dots to create better looking swarms?
mwaskom hinted to me in the comments how to solve this.
It is even stated in the swamplot doku:
Note that arranging the points properly requires an accurate transformation between data and point coordinates. This means that non-default axis limits should be set before drawing the swarm plot.
Setting an existing axis to log-scale and use this for the plot:
fig = plt.figure() # create figure
rect = 0,0,1,1 # create an rectangle for the new axis
log_ax = fig.add_axes(rect) # create a new axis (or use an existing one)
log_ax.set_yscale("log") # log first
sns.swarmplot(x=self.dte.label_temperature, y=self.dte.label_current, hue=self.dte.label_voltage, data = df, ax = log_ax)
This yields in the correct and desired plotting behaviour:

ValueError when using matplotlib tight_layout()

Ok, this is my first time asking a question on here, so please be patient with me ;-)
I'm trying to create a series of subplots (with two y-axes each) in a figure using matplotlib and then saving that figure. I'm using GridSpec to create a grid for the subplots and realised that they're overlapping a little, which I don't want. So I'm trying to use tight_layout() to sort this out, which according to the matplotlib documentation should work just fine. Simplifying things a bit, my code looks something like this:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(num=None, facecolor='w', edgecolor='k')
grid = gridspec.GridSpec(2, numRows)
# numRows comes from the number of subplots required
# then I loop over all the data files I'm importing and create a subplot with two y-axes each time
ax1 = fig.add_subplot(grid[column, row])
# now I do all sorts of stuff with ax1...
ax2 = ax1.twinx()
# again doing some stuff here
After the loop for data processing is done and I have created all the subplots, I eventually end with
fig.tight_layout()
fig.savefig(str(location))
As far as I can work out, this should work, however when calling tight_layout(), I get a ValueError from the function self.subplotpars: left cannot be >= right. My question is: How do I figure out what's causing this error and how do I fix it?
I've had this error before, and I have a solution that worked for me. I'm not sure if it will work for you though. In matplotlib, the command
plt.fig.subplots_adjust()
can be used to sort of stretch the plot. The left and bottom stretch more the smaller the number gets, while the top and right stretch more the greater the number is. So if left is greater than or equal to the right, or bottom is greater than or equal to the top, than the graph would kind of flip over. I adjusted my command to look like this:
fig = plt.figure()
fig.subplots_adjust(bottom = 0)
fig.subplots_adjust(top = 1)
fig.subplots_adjust(right = 1)
fig.subplots_adjust(left = 0)
Then you can fill in your own numbers to adjust this, as long as you keep the left and bottom smaller. I hope this fixes your problem.

adding extra axis ticks using matplotlib

I have a simple plot code as
plt.plot(x,y)
plt.show()
I want to add some extra ticks on the x-axis in addition to the current ones, let's say at
extraticks=[2.1, 3, 7.6]
As you see I do not have a pattern for ticks so I do not want to increase the tick frequency for the whole axis; just keep the original ones and add those extras...
Is it possible, at all?
Regards
Yes, you can try something like:
plt.xticks(list(plt.xticks()[0]) + extraticks)
The function to use is xticks(). When called without arguments, it returns the current ticks. Calling it with arguments, you can set the tick positions and, optionally, labels.
For the sake of completeness, I would like to give the OO version of #Lev-Levitsky's great answer:
lines = plt.plot(x,y)
ax = lines[0].axes
ax.set_xticks(list(ax.get_xticks()) + extraticks)
Here we use the Axes object extracted from the Lines2D sequence returned by plot. Normally if you are using the OO interface you would already have a reference to the Axes up front and you would call plot on that instead of on pyplot.
Corner Caveat
If for some reason you have modified your axis limits (e.g, by programatically zooming in to a portion of the data), you will need to restore them after this operation:
lim = ax.get_xlim()
ax.set_xticks(list(ax.get_xticks()) + extraticks)
ax.set_xlim(lim)
Otherwise, the plot will make the x-axis show all the available ticks on the axis.

Categories

Resources