混合水平和垂直刻度

时间:2021-05-27 23:46:27

标签: python matplotlib xticks

我有下面显示的示例图。如何使第一个和第三个 x 轴水平刻度,第二个和第四个刻度垂直?

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y)
plt.xticks(x, labels, rotation='vertical')
plt.margins(0.2)
plt.subplots_adjust(bottom=0.15)
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:1)

不确定是否有自动执行此操作的方法,但您可以为每个刻度“手动”执行此操作:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y)
plt.xticks(x, labels, rotation='vertical')
plt.margins(0.2)
plt.subplots_adjust(bottom=0.15)
plt.show()

# getting the labels from the axis
ticks_labels = plt.gca().get_xticklabels()

# rotating first and third ticks
ticks_labels[0].set_rotation('horizontal')
ticks_labels[2].set_rotation('horizontal')

Graph with the horizontal labels

ticks_labels 列表中的每一项都是一个 Text artist,因此您几乎可以更改所有内容(大小、颜色、位置等)

相关问题