and the x axis’ ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?
回答 0
您可以使用以下命令显式设置要在标记上打勾的位置plt.xticks:
plt.xticks(np.arange(min(x), max(x)+1,1.0))
例如,
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()
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()
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,
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()
回答 1
另一种方法是设置轴定位器:
import matplotlib.ticker as plticker
loc = plticker.MultipleLocator(base=1.0)# this locator puts ticks at regular intervals
ax.xaxis.set_major_locator(loc)
根据您的需要,有几种不同类型的定位器。
这是一个完整的示例:
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()
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()
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.
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)
回答 5
这是一个古老的话题,但是我时不时地碰到这个问题,并做了这个功能。这很方便:
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)
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.
回答 6
我开发了一个优雅的解决方案。考虑我们有X轴,还有X中每个点的标签列表。
例:
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']
假设我只想显示“ feb”和“ jun”的刻度标签
xlabelsnew =[]for i in xlabels:if i notin['feb','jun']:
i =' '
xlabelsnew.append(i)else:
xlabelsnew.append(i)
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)else0), xMin - abs((xMin % step))return range(dMin, dMax, step)
样本输出
# 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]
样品用量
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()
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)
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).