我想对图中选定的几个勾号标签做一些修改。

例如,如果我这样做:

label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')

更改了标记标签的字体大小和方向。

然而,如果尝试:

label.set_text('Foo')

没有修改勾号标签。如果我这样做:

print label.get_text()

什么都没有印出来。

这里还有一些奇怪的事情。当我试着这样做时:

import matplotlib.pyplot as plt
import numpy as np

axes = plt.figure().add_subplot(111)
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
axes.plot(t, s)
for ticklabel in axes.get_xticklabels():
    print(ticklabel.get_text())

只打印空字符串,但plot包含标记为'0.0'、'0.5'、'1.0'、'1.5'和'2.0'的刻度。


当前回答

如果你不使用fig和ax,你想修改所有的标签(例如标准化),你可以这样做:

labels, locations = plt.yticks()
plt.yticks(labels, labels/max(labels))

其他回答

matplotlib.axes.Axes.set_xticks, or matplotlib.axes.Axes.set_yticks for the y-axis, can be used to change the ticks and labels beginning with matplotlib 3.5.0. These are for the object oriented interface. If using the pyplot state-based interface, use plt.xticks or plt.yticks, as shown in other answers. In general terms, pass a list / array of numbers to the ticks parameter, and a list / array strings to the labels parameter. In this case, the x-axis is comprised of continuous numeric values, so there are no set Text labels, as thoroughly explained in this answer. This is not the case when plots have discrete ticks (e.g. boxplot, barplot). [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, '')] is returned by ax.get_xticklabels() [-0.25 0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. 2.25] is returned by ax.get_xticks() type(ax.get_xticks()) is <class 'numpy.ndarray'> type(ax.get_xticks()[0]) is <class 'numpy.float64'> Since the OP is trying to replace a numeric label with a str, all of the values in the ndarray must be converted to str type, and the value to be changed can be updated. Tested in python 3.10 and matplotlib 3.5.2

import numpy as np
import matplotlib.pyplot as plt

# create figure and axes
fig, ax = plt.subplots(figsize=(8, 6))

# plot data
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

# plot
ax.plot(t, s)

# get the xticks, which are the numeric location of the ticks
xticks = ax.get_xticks()

# get the xticks and convert the values in the array to str type
xticklabels = list(map(str, ax.get_xticks()))

# update the string to be changed
xticklabels[1] = 'Test'

# set the xticks and the labels
_ = ax.set_xticks(xticks, xticklabels)

注意,更改xticklabels时,x轴偏移量不会保留。但是,正确的值没有偏移量。

# create figure and axes
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 6), sharex=False)

# plot data
t = np.linspace(0, 1500000, 100)
s = t**2

# plot
ax1.plot(t, s)
ax2.plot(t, s)

# get the xticks, which are the numeric location of the ticks
xticks = ax2.get_xticks()

# get the xticks and convert the values in the array to str type
xticklabels = list(map(str, ax2.get_xticks()))

# update the string to be changed
xticklabels[1] = 'Test'

# set the xticks and the labels
_ = ax2.set_xticks(xticks, xticklabels, rotation=90)

也可以使用pylab和xticks来实现这一点

import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()

https://matplotlib.org/stable/gallery/ticks_and_spines/ticklabels_rotation.html

这个问题被问到已经有一段时间了。截至今天(matplotlib 2.2.2),经过一些阅读和试验,我认为最佳/适当的方式如下:

Matplotlib有一个名为ticker的模块,它“包含支持完全可配置的标记定位和格式化的类”。为了从图中修改一个特定的tick,以下对我来说是有效的:

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np 

def update_ticks(x, pos):
    if x == 0:
        return 'Mean'
    elif pos == 6:
        return 'pos is 6'
    else:
        return x

data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()

警告!X是tick的值,pos是它在坐标轴上的相对位置。注意,pos的值从1开始,而不是在索引时通常从0开始。


在我的例子中,我试图用百分比值格式化直方图的y轴。mticker有另一个名为PercentFormatter的类,它可以很容易地做到这一点,而不需要像以前那样定义一个单独的函数:

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np 

data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
weights = np.ones_like(data) / len(data)
ax.hist(data, bins=25, weights=weights, edgecolor='black')
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
plt.show()

在本例中,xmax是对应于100%的数据值。百分比计算为x / xmax * 100,这就是为什么我们修正xmax=1.0。此外,decimals是指在该点后放置的小数位数。

如果你不使用fig和ax,你想修改所有的标签(例如标准化),你可以这样做:

labels, locations = plt.yticks()
plt.yticks(labels, labels/max(labels))

这也适用于matplotlib 3:

x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']

plt.xticks(x1, squad, rotation=45)