如何使用自定义的“字符串”重命名x标签?

时间:2019-05-11 09:01:36

标签: python python-3.x matplotlib plot

我有一个图,其中x标签代表工作日,而不是从星期一到星期日,它们的范围是0到6。我想将此轴转换为从星期一到星期日的范围(星期一代表0,星期一代表1)周二...,周六... 6):

     import matplotlib.pyplot as plt
     plt.style.use('fivethirtyeight')
     plt.rcParams["figure.figsize"] = [16,9]
     x = Res['weekday']
     y = Res['Ammonia']
     plt.scatter(x,y)
     plt.xlabel('Weekday')
     plt.ylabel('Ammonia Level')
     plt.title('Ammonia by Weekday')
     plt.show()

enter image description here

2 个答案:

答案 0 :(得分:0)

使用matplotlib.pyplot.xticks

在您的情况下,它将是:

xlabels = ["Monday", "Tuesday", ...]
plt.xticks(range(7), xlabels)

答案 1 :(得分:0)

我发现解决这个问题是违反直觉的,因为plt.xticks不起作用,并且ax.xticks的默认值似乎是从1开始的,因此如果您不这样做,则会使标签对齐错误将其设置为range(7)

import random
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

# Create some fake data
x_axis = [[x for y in range(50)] for x in range(7)]
y_axis = [[random.random() * 10 for y in range(50)] for x in range(7)]

# Create figure and axis objects
fig, ax = plt.subplots()
ax.scatter(x_axis, y_axis)

# Your existing code
plt.xlabel('Weekday')
plt.ylabel('Ammonia Level')
plt.title('Ammonia by Weekday')

# Set the xtick labels on the axis object
ax.set_xticks(range(7))
ax.set_xticklabels(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])

plt.show()