I am trying to fix how python plots my data.
Say:
x = [0,5,9,10,15]
y = [0,1,2,3,4]
matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()
The x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
You could explicitly set where you want to tick marks with plt.xticks:
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
For example,
import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()
(np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.)
The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set.
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
Here's a runnable example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()
Another approach is to set the axis locator:
import matplotlib.ticker as plticker
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
There are several different types of locator depending upon your needs.
Here is a full example:
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
loc = plticker.MultipleLocator(base=1.0) # this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
plt.show()
I like this solution (from the Matplotlib Plotting Cookbook):
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
tick_spacing = 1
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()
This solution give you explicit control of the tick spacing via the number given to ticker.MultipleLocater(), allows automatic limit determination, and is easy to read later.
In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.
ax.set_xticks(ax.get_xticks()[::2])
if you just want to set the spacing a simple one liner with minimal boilerplate:
plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))
also works easily for minor ticks:
plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(1))
a bit of a mouthfull, but pretty compact
This is a bit hacky, but by far the cleanest/easiest to understand example that I've found to do this. It's from an answer on SO here:
Cleanest way to hide every nth tick label in matplotlib colorbar?
for label in ax.get_xticklabels()[::2]:
label.set_visible(False)
Then you can loop over the labels setting them to visible or not depending on the density you want.
edit: note that sometimes matplotlib sets labels == '', so it might look like a label is not present, when in fact it is and just isn't displaying anything. To make sure you're looping through actual visible labels, you could try:
visible_labels = [lab for lab in ax.get_xticklabels() if lab.get_visible() is True and lab.get_text() != '']
plt.setp(visible_labels[::2], visible=False)
This is an old topic, but I stumble over this every now and then and made this function. It's very convenient:
import matplotlib.pyplot as pp
import numpy as np
def resadjust(ax, xres=None, yres=None):
"""
Send in an axis and I fix the resolution as desired.
"""
if xres:
start, stop = ax.get_xlim()
ticks = np.arange(start, stop + xres, xres)
ax.set_xticks(ticks)
if yres:
start, stop = ax.get_ylim()
ticks = np.arange(start, stop + yres, yres)
ax.set_yticks(ticks)
One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. Then do
gca().set_ylim(top=new_top) # for example
and run the resadjust function again.
I developed an inelegant solution. Consider that we have the X axis and also a list of labels for each point in X.
Example:
import matplotlib.pyplot as plt
x = [0,1,2,3,4,5]
y = [10,20,15,18,7,19]
xlabels = ['jan','feb','mar','apr','may','jun']
Let's say that I want to show ticks labels only for 'feb' and 'jun'
xlabelsnew = []
for i in xlabels:
if i not in ['feb','jun']:
i = ' '
xlabelsnew.append(i)
else:
xlabelsnew.append(i)
Good, now we have a fake list of labels. First, we plotted the original version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
Now, the modified version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabelsnew,rotation=45)
plt.show()
Pure Python Implementation
Below's a pure python implementation of the desired functionality that handles any numeric series (int or float) with positive, negative, or mixed values and allows for the user to specify the desired step size:
import math
def computeTicks (x, step = 5):
"""
Computes domain with given step encompassing series x
# params
x - Required - A list-like object of integers or floats
step - Optional - Tick frequency
"""
xMax, xMin = math.ceil(max(x)), math.floor(min(x))
dMax, dMin = xMax + abs((xMax % step) - step) + (step if (xMax % step != 0) else 0), xMin - abs((xMin % step))
return range(dMin, dMax, step)
Sample Output
# Negative to Positive
series = [-2, 18, 24, 29, 43]
print(list(computeTicks(series)))
[-5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
# Negative to 0
series = [-30, -14, -10, -9, -3, 0]
print(list(computeTicks(series)))
[-30, -25, -20, -15, -10, -5, 0]
# 0 to Positive
series = [19, 23, 24, 27]
print(list(computeTicks(series)))
[15, 20, 25, 30]
# Floats
series = [1.8, 12.0, 21.2]
print(list(computeTicks(series)))
[0, 5, 10, 15, 20, 25]
# Step – 100
series = [118.3, 293.2, 768.1]
print(list(computeTicks(series, step = 100)))
[100, 200, 300, 400, 500, 600, 700, 800]
Sample Usage
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(computeTicks(x))
plt.show()
Notice the x-axis has integer values all evenly spaced by 5, whereas the y-axis has a different interval (the matplotlib default behavior, because the ticks weren't specified).
Generalisable one liner, with only Numpy imported:
ax.set_xticks(np.arange(min(x),max(x),1))
Set in the context of the question:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [0,5,9,10,15]
y = [0,1,2,3,4]
ax.plot(x,y)
ax.set_xticks(np.arange(min(x),max(x),1))
plt.show()
How it works:
fig, ax = plt.subplots() gives the ax object which contains the axes.
np.arange(min(x),max(x),1) gives an array of interval 1 from the min of x to the max of x. This is the new x ticks that we want.
ax.set_xticks() changes the ticks on the ax object.
xmarks=[i for i in range(1,length+1,1)]
plt.xticks(xmarks)
This worked for me
if you want ticks between [1,5] (1 and 5 inclusive) then replace
length = 5
Since None of the above solutions worked for my usecase, here I provide a solution using None (pun!) which can be adapted to a wide variety of scenarios.
Here is a sample piece of code that produces cluttered ticks on both X and Y axes.
# Note the super cluttered ticks on both X and Y axis.
# inputs
x = np.arange(1, 101)
y = x * np.log(x)
fig = plt.figure() # create figure
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xticks(x) # set xtick values
ax.set_yticks(y) # set ytick values
plt.show()
Now, we clean up the clutter with a new plot that shows only a sparse set of values on both x and y axes as ticks.
# inputs
x = np.arange(1, 101)
y = x * np.log(x)
fig = plt.figure() # create figure
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xticks(x)
ax.set_yticks(y)
# which values need to be shown?
# here, we show every third value from `x` and `y`
show_every = 3
sparse_xticks = [None] * x.shape[0]
sparse_xticks[::show_every] = x[::show_every]
sparse_yticks = [None] * y.shape[0]
sparse_yticks[::show_every] = y[::show_every]
ax.set_xticklabels(sparse_xticks, fontsize=6) # set sparse xtick values
ax.set_yticklabels(sparse_yticks, fontsize=6) # set sparse ytick values
plt.show()
Depending on the usecase, one can adapt the above code simply by changing show_every and using that for sampling tick values for X or Y or both the axes.
If this stepsize based solution doesn't fit, then one can also populate the values of sparse_xticks or sparse_yticks at irregular intervals, if that is what is desired.
You can loop through labels and show or hide those you want:
for i, label in enumerate(ax.get_xticklabels()):
if i % interval != 0:
label.set_visible(False)
Related
How do i set xticks to 'a different interval'
For instance:
plt.plot(1/(np.arange(0.1,3,0.1)))
returns:
If I would like the x axis to be on a scale from 0 to 3, how can i do that? I've tried
plt.xticks([0,1,2])
but that returns:
You want to learn about plt.xlim and adjacent functions. This causes the X axis to have limits (minimum, maximum) that you specify. Otherwise Matplotlib decides for you based on the values you try to plot.
y = 1 / np.arange(0.1,3,0.1)
plt.plot(y)
plt.xlim(0, 3) # minimum 0, maximum 3
plt.show()
Your plot uses only Y values, so the X values are automatically chosen to be 1, 2, 3, ... to pair up with each Y value you provide.
If you desire to determine the X too, you can do that:
x = np.arange(0.1,3,0.1)
y = 1/x
plt.plot(x, y)
plt.xticks([0,1,2,3]) # ticks at those positions, if you don't like the automatic ones
plt.show()
You can use numpy.arange() to get the desired range with a specific step:
import matplotlib.pyplot as plt
import numpy as np
y = 1/(np.arange(0.1,3,0.1))
plt.tight_layout()
plt.plot(y)
plt.xticks(np.arange(0, len(y), 6), [str(round(i, 2)) for i in np.arange(0, 3, (3*6)/len(y))])
plt.show()
Also, you can see more examples of xticks() on the official matplotlib documentation.
I want to use matpoltlib to make a plot that with a constant y axis(always from 0 to 14 and the gap is 1), since I want to make labels for them and my dot values will be(x, y) where y is from 0 to 14 gap 1, and a changing x axis. I already tried to play with y ticks. And here is my code for that:
fig, ax = plt.subplots()
fig.canvas.draw()
plt.yticks(np.arange(0, 14, 1))
labels = [item.get_text() for item in ax.get_yticklabels()]
labels[1] = 'Not Detected'
labels[2] = 'A/G'
labels[3] = 'G/G'
labels[4] = 'C/T'
labels[5] = 'C/C'
labels[6] = 'A/A'
labels[7] = '-1'
labels[8] = 'ε3/ε3'
labels[9] = 'A/C'
labels[10] = 'T/T'
labels[11] = 'C/G'
labels[12] = 'ε2/ε3'
labels[13] = 'G/T'
ax.set_yticklabels(labels)
what I'm thinking about is to use some values or lines with white color so those y axis will appear. But I'm looking for a more efficient way of doing it. And here is the diagram I generated with the current code. It only shows C/C right now and I want all labels to appear in the diagram.
I tried draw white points with:
x1 = np.arange(n)
y1 = np.arange(1,15,1)
plt.scatter(x1,y1,color = 'white')
Which did give me what I want: But I was wondering whether there is a lib setting that can do this.
I would recommend just using a fixed locator and fixed formatter for your y axis. The function, ax.set_yticklabels() is simply a convenience wrapper for these tick methods.
I would also recommend having your y_labels in a list or using a loop structure as this is a more generalizable and modifiable implementation.
If I'm understanding the goals of your plot correctly, something like this may work well for you.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
#make some data
x = np.arange(25)
y = np.random.randint(1, 14, size=25)
#convert y labels to a list
y_labels = [
'Not Detected','A/G','G/G','C/T','C/C','A/A',
'-1','ε3/ε3', 'A/C','T/T','C/G','ε2/ε3','G/T'
]
#define figure/ax and set figsize
fig, ax = plt.subplots(figsize=(12,8))
#plot data, s is marker size, it's points squared
ax.scatter(x, y, marker='x', s=10**2, color='#5d2287', linewidth=2)
#set major locator and formatter to fixed, add grid, hide top/right spines
locator = ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(np.arange(1, 14)))
formatter = ax.yaxis.set_major_formatter(mpl.ticker.FixedFormatter(y_labels))
grid = ax.grid(axis='y', dashes=(8,3), alpha=0.3, color='gray')
spines = [ax.spines[x].set_visible(False) for x in ['top','right']]
params = ax.tick_params(labelsize=12) #increase label font size
I would like to calculate several functions including ln(x) on an interval going from 1 to 10. However, I would like to plot on an interval of x ranging from x[-1, 10].
So far, I could not modify the ticks as I want, the labels are following the size of my ln(x) rather than the value of x itself:
axiss = np.linspace(-1,10,12)
x = np.linspace(-1, 10, 1002)
s = int(np.where(x == 1)[0])
fig, ax = plt.subplots()
ax.plot(np.log(x[s:-1]), label='ln(x)')
ax.plot(1/x[s:-1], label='1/x')
ax.plot(-1/(x[s:-1]**2), label='-1/x2')
ax.plot(2/(x[s:-1]**3), label='2/x3')
ax.legend()
ax.set_xlim(-100, 1000)
ax.set_xticklabels(axiss)
How could I do to define a range for my x-axis, but only calculate the functions on a part of it ?
I tried:
ax.plot(x, np.log(x[s:-1]), label='ln(x)')
but of course I have a length issue.
Thank you !
ps: yes I already searched online for ways to do it, asking here is the last resort that I have
You can explicity give both x and y lists to matplotlib. This also avoids the need to set the xtick labels manually.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 10, 1001) # don't divide by 0.0
x_for_ln = np.linspace(0.001, 10, 1001)
fig, ax = plt.subplots()
ax.plot(x_for_ln, np.log(x_for_ln), label='ln(x)')
ax.plot(x, 1/x, label='1/x')
ax.plot(x, -1/(x**2), label='-1/x2')
ax.plot(x, 2/(x**3), label='2/x3')
ax.legend()
ax.set_ylim(-10, 10)
I use automatic axes range for data.
For example, when I use x data between -29 and +31 and I do
ax = plt.gca()
xsta, xend = ax.get_xlim()
I get -30 and 40, which does not appropriately describe data range. I would like see that axes ranges are rounded to 5, i.e. -30 and 35 for limits.
Is it possible to do that? Or, alternatively, is it possible to get exact ranges of x-axes data (-29,31) and then write an algorithm to change that manually (using set_xlim)?
Thanks for help.
First off, let's set up a simple example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
plt.show()
If you'd like to know the data range for manually specifying things as you mentioned, you can use:
ax.xaxis.get_data_interval()
ax.yaxis.get_data_interval()
However, it's very common to want to change to a simple padding of the data limits. In that case, use ax.margins(some_percentage). For example, this would pad the limits with 5% of the data range:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.margins(0.05)
plt.show()
To go back to your original scenario, you could manually make the axes limits only use multiples of 5 (but not change the ticks, etc):
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
multiplier = 5.0
for axis, setter in [(ax.xaxis, ax.set_xlim), (ax.yaxis, ax.set_ylim)]:
vmin, vmax = axis.get_data_interval()
vmin = multiplier * np.floor(vmin / multiplier)
vmax = multiplier * np.ceil(vmax / multiplier)
setter([vmin, vmax])
plt.show()
We could also accomplish the same thing by subclassing the locator for each axis:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoLocator
class MyLocator(AutoLocator):
def view_limits(self, vmin, vmax):
multiplier = 5.0
vmin = multiplier * np.floor(vmin / multiplier)
vmax = multiplier * np.ceil(vmax / multiplier)
return vmin, vmax
fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.xaxis.set_major_locator(MyLocator())
ax.yaxis.set_major_locator(MyLocator())
ax.autoscale()
plt.show()
To set the axis xlim to the exact range of the data, use the ax.xlim() method in combination with the built in min() and max() functions:
#x could be a list like [0,3,5,6,15]
ax = plt.gca()
ax.xlim([min(x), max(x)]) # evaluates to ax.xlim([0, 15]) with example data above
When you know you want it in multiples of 5, modify the limits according to the x-range of your data:
import math
import matplotlib.pyplot as pet
#your plotting here
xmin = min( <data_x> )
xmax = max( <data_x> )
ax = plt.gca()
ax.set_xlim( [5*math.floor(xmin/5.0), 5*math.ceil(xmax/5.0)] )
Note that the division has to be by the float 5.0, as int/int neglects the fractional part. For example xmax=6 in 5*math.ceil(6/5) would return 5, which cuts off your data, whereas 5*math.ceil(6/5.0) gives the desired 5*math.ceil(1.2) = 5*2 =10.
I'm trying to plot some data using pyplot, and then 'zoom in' by using xlim() the x axis. However, the new plot doesn't rescale the y axis when I do this - am I doing something wrong?
Example - in this code, the plot y-axis range still takes a maximum of 20, rather than 10.:
from pylab import *
x = range(20)
y = range(20)
xlim(0,10)
autoscale(enable=True, axis='y', tight=None)
scatter(x,y)
show()
close()
Realize this is an ancient question, but this is how I've (messily) gotten around the issue:
use .plot() instead of .scatter()
access plot data later (even after a figure is returned somewhere) with ax.get_lines()[0].get_xydata()
use that data to rescale y axis to xlims
Snippet should work:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
x = range(20)
y = range(20)
xlims = [0, 10]
ax.set_xlim(xlims)
ax.plot(x, y, marker='.', ls='')
# pull plot data
data = ax.get_lines()[0].get_xydata()
# cut out data in xlims window
data = data[np.logical_and(data[:, 0] >= xlims[0], data[:, 0] <= xlims[1])]
# rescale y
ax.set_ylim(np.min(data[:, 1]), np.max(data[:, 1]))
plt.show()
I don't know, though you could try manually filtering the points with
scatter([(a,b) for a,b in zip(x,y) if a>0 and a<10])