问题:在python matplotlib中旋转轴文本

我不知道如何在X轴上旋转文本。这是一个时间戳记,因此随着样本数量的增加,它们越来越近,直到它们重叠。我想将文本旋转90度,以使样本靠得更近,它们不会重叠。

下面是我所拥有的,除了我不知道如何旋转X轴文本外,它可以正常工作。

import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 8}

matplotlib.rc('font', **font)

values = open('stats.csv', 'r').readlines()

time = [datetime.datetime.fromtimestamp(float(i.split(',')[0].strip())) for i in values[1:]]
delay = [float(i.split(',')[1].strip()) for i in values[1:]]

plt.plot(time, delay)
plt.grid(b='on')

plt.savefig('test.png')

I can’t figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I’d like to rotate the text 90 degrees so as the samples get closer together, they aren’t overlapping.

Below is what I have, it works fine with the exception that I can’t figure out how to rotate the X axis text.

import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 8}

matplotlib.rc('font', **font)

values = open('stats.csv', 'r').readlines()

time = [datetime.datetime.fromtimestamp(float(i.split(',')[0].strip())) for i in values[1:]]
delay = [float(i.split(',')[1].strip()) for i in values[1:]]

plt.plot(time, delay)
plt.grid(b='on')

plt.savefig('test.png')

回答 0

这对我有用:

plt.xticks(rotation=90)

This works for me:

plt.xticks(rotation=90)

回答 1

简单的方法

如此处所述matplotlib.pyplot figure该类中存在一个现有方法,该方法可以自动轮换日期以适合您的身材。

您可以在绘制数据后调用它(即ax.plot(dates,ydata)

fig.autofmt_xdate()

如果您需要进一步格式化标签,请查看上面的链接。

非日期时间对象

根据languitar的评论,我建议的非datetime方法xticks在缩放等情况下无法正确更新。如果它不是datetime用作x轴数据的对象,则应遵循Tommy的回答

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

Easy way

As described here, there is an existing method in the matplotlib.pyplot figure class that automatically rotates dates appropriately for you figure.

You can call it after you plot your data (i.e.ax.plot(dates,ydata) :

fig.autofmt_xdate()

If you need to format the labels further, checkout the above link.

Non-datetime objects

As per languitar‘s comment, the method I suggested for non-datetime xticks would not update correctly when zooming, etc. If it’s not a datetime object used as your x-axis data, you should follow Tommy‘s answer:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

回答 2

这里有许多“正确”的答案,但由于我认为一些细节中遗漏了一些,因此我将再添加一个。OP要求旋转90度,但我将更改为45度,因为当您使用非零或90度的角度时,还应该更改水平对齐方式;否则,您的标签将偏离中心并产生误导性(我猜很多来这里的人都想将轴旋转到90以外的位置)。

最简单/最少的代码

选项1

plt.xticks(rotation=45, ha='right')

如前所述,如果您宁愿采用面向对象的方法,那可能也不是所希望的。

选项2

另一种快速方法(该方法适用于日期对象,但似乎可以在任何标签上使用;不过建议不要这样做):

fig.autofmt_xdate(rotation=45)

fig 您通常可以从:

  • fig = plt.figure()
  • fig, ax = plt.subplots()
  • fig = ax.figure

面向对象/直接与 ax

选项3a

如果您有标签列表:

labels = ['One', 'Two', 'Three']
ax.set_xticklabels(labels, rotation=45, ha='right')

选项3b

如果要从当前绘图中获取标签列表:

# Unfortunately you need to draw your figure first to assign the labels,
# otherwise get_xticklabels() will return empty strings.
plt.draw()
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')

选项4

与上述类似,但手动循环。

for label in ax.get_xticklabels():
  label.set_rotation(45)
  label.set_ha('right')

选项5

我们仍在此处使用pyplot(as plt),但是它是面向对象的,因为我们正在更改特定ax对象的属性。

plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

选项6

此选项很简单,但是AFAIK不能以这种方式设置标签水平对齐,因此,如果角度不为90,则另一个选项可能会更好。

ax.tick_params(axis='x', labelrotation=45)

编辑: 关于此确切的“错误”的讨论,并且可能会针对v3.2.0以下问题进行修复:https : //github.com/matplotlib/matplotlib/issues/13774

Many “correct” answers here but I’ll add one more since I think some details are left out of several. The OP asked for 90 degree rotation but I’ll change to 45 degrees because when you use an angle that isn’t zero or 90, you should change the horizontal alignment as well; otherwise your labels will be off-center and a bit misleading (and I’m guessing many people who come here want to rotate axes to something other than 90).

Easiest / Least Code

Option 1

plt.xticks(rotation=45, ha='right')

As mentioned previously, that may not be desirable if you’d rather take the Object Oriented approach.

Option 2

Another fast way (it’s intended for date objects but seems to work on any label; doubt this is recommended though):

fig.autofmt_xdate(rotation=45)

fig you would usually get from:

  • fig = plt.figure()
  • fig, ax = plt.subplots()
  • fig = ax.figure

Object-Oriented / Dealing directly with ax

Option 3a

If you have the list of labels:

labels = ['One', 'Two', 'Three']
ax.set_xticklabels(labels, rotation=45, ha='right')

Option 3b

If you want to get the list of labels from the current plot:

# Unfortunately you need to draw your figure first to assign the labels,
# otherwise get_xticklabels() will return empty strings.
plt.draw()
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')

Option 4

Similar to above, but loop through manually instead.

for label in ax.get_xticklabels():
  label.set_rotation(45)
  label.set_ha('right')

Option 5

We still use pyplot (as plt) here but it’s object-oriented because we’re changing the property of a specific ax object.

plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

Option 6

This option is simple, but AFAIK you can’t set label horizontal align this way so another option might be better if your angle is not 90.

ax.tick_params(axis='x', labelrotation=45)

Edit: There’s discussion of this exact “bug” and a fix is potentially slated for v3.2.0: https://github.com/matplotlib/matplotlib/issues/13774


回答 3

尝试pyplot.setp。我认为您可以执行以下操作:

x = range(len(time))
plt.xticks(x,  time)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.plot(x, delay)

Try pyplot.setp. I think you could do something like this:

x = range(len(time))
plt.xticks(x,  time)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.plot(x, delay)

回答 4

来自的Appart

plt.xticks(rotation=90)

这也是可能的:

plt.xticks(rotation='vertical')

Appart from

plt.xticks(rotation=90)

this is also possible:

plt.xticks(rotation='vertical')

回答 5

我想出了一个类似的例子。同样,rotation关键字是..嗯,这是关键。

from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;

I came up with a similar example. Again, the rotation keyword is.. well, it’s key.

from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;

回答 6

我的答案受到cjohnson318答案的启发,但我不想提供标签的硬编码列表。我想旋转现有标签:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

My answer is inspired by cjohnson318’s answer, but I didn’t want to supply a hardcoded list of labels; I wanted to rotate the existing labels:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

回答 7

如果使用plt

plt.xticks(rotation=90)

如果使用熊猫或海生动物进行绘图,则以绘图的ax轴为例:

ax.set_xticklabels(ax.get_xticklabels(), rotation=90)

完成上述操作的另一种方法:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

If using plt:

plt.xticks(rotation=90)

In case of using pandas or seaborn to plot, assuming ax as axes for the plot:

ax.set_xticklabels(ax.get_xticklabels(), rotation=90)

Another way of doing the above:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

回答 8

如果要对轴对象施加旋转,最简单的方法是使用tick_params。例如。

ax.tick_params(axis='x', labelrotation=90)

Matplotlib文档参考在这里

当您有由返回的轴数组时,此功能很有用plt.subplots,并且比使用更方便,set_xticks因为在这种情况下,您还需要设置刻度标签,并且还需要遍历刻度线(因为明显的原因)

If you want to apply rotation on the axes object, the easiest way is using tick_params. For example.

ax.tick_params(axis='x', labelrotation=90)

Matplotlib documentation reference here.

This is useful when you have an array of axes as returned by plt.subplots, and it is more convenient than using set_xticks because in that case you need to also set the tick labels, and also more convenient that those that iterate over the ticks (for obvious reasons)


回答 9

import pylab as pl
pl.xticks(rotation = 90)
import pylab as pl
pl.xticks(rotation = 90)

回答 10

这将取决于您要绘制的内容。

import matplotlib.pyplot as plt

 x=['long_text_for_a_label_a',
    'long_text_for_a_label_b',
    'long_text_for_a_label_c']
y=[1,2,3]
myplot = plt.plot(x,y)
for item in myplot.axes.get_xticklabels():
    item.set_rotation(90)

对于给您一个轴对象的大熊猫和海豚:

df = pd.DataFrame(x,y)
#pandas
myplot = df.plot.bar()
#seaborn 
myplotsns =sns.barplot(y='0',  x=df.index, data=df)
# you can get xticklabels without .axes cause the object are already a 
# isntance of it
for item in myplot.get_xticklabels():
    item.set_rotation(90)

如果您需要旋转标签,则可能还需要更改字体大小,可以使用font_scale=1.0该方法。

It will depend on what are you plotting.

import matplotlib.pyplot as plt

 x=['long_text_for_a_label_a',
    'long_text_for_a_label_b',
    'long_text_for_a_label_c']
y=[1,2,3]
myplot = plt.plot(x,y)
for item in myplot.axes.get_xticklabels():
    item.set_rotation(90)

For pandas and seaborn that give you an Axes object:

df = pd.DataFrame(x,y)
#pandas
myplot = df.plot.bar()
#seaborn 
myplotsns =sns.barplot(y='0',  x=df.index, data=df)
# you can get xticklabels without .axes cause the object are already a 
# isntance of it
for item in myplot.get_xticklabels():
    item.set_rotation(90)

If you need to rotate labels you may need change the font size too, you can use font_scale=1.0 to do that.


回答 11

要将x轴标签旋转到90度

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

To rotate the x-axis label to 90 degrees

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

回答 12

最简单的解决方案是使用:

plt.xticks(rotation=XX)

但是也

# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=X.XX)

例如,对于日期,我使用了rotation = 45和bottom = 0.20,但是您可以对数据进行一些测试

The simplest solution is to use:

plt.xticks(rotation=XX)

but also

# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=X.XX)

e.g for dates I used rotation=45 and bottom=0.20 but you can do some test for your data


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。