Python 在Matplotlib打印中将轴范围更改为非连续数

Python 在Matplotlib打印中将轴范围更改为非连续数,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个数据帧,'x'列类似于[8,9,10,…,24,1,2,3,…,7]。当我尝试绘制它时,x轴仍将从1、2、3开始。。。我能把起点从8改成24,然后从1改成7吗?代码如下: import pandas as pd import numpy as np import matplotlib.pyplot as plt l1 = [x for x in range(1, 25)] l2 = l1[7:] + l1[:7] arr1 = np.asarray(l2) arr1 y = np.r

我有一个数据帧,'x'列类似于[8,9,10,…,24,1,2,3,…,7]。当我尝试绘制它时,x轴仍将从1、2、3开始。。。我能把起点从8改成24,然后从1改成7吗?代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

l1 = [x for x in range(1, 25)]
l2 = l1[7:] + l1[:7]
arr1 = np.asarray(l2)
arr1

y = np.random.rand(24)

df = pd.DataFrame({'x': arr1, 'y': y})

fig = plt.figure()

ax = fig.add_subplot(111)

ax.bar(df['x'],df['y'])
ax.set_ylim(0, 1)

plt.show()

print(df)

     x         y
0    8  0.354536
1    9  0.418379
2   10  0.902957
3   11  0.026550
4   12  0.560771
5   13  0.804618
6   14  0.114657
7   15  0.969412
8   16  0.595874
9   17  0.193734
10  18  0.740406
11  19  0.848634
12  20  0.799882
13  21  0.674117
14  22  0.453562
15  23  0.009416
16  24  0.124332
17   1  0.232094
18   2  0.405055
19   3  0.034836
20   4  0.627928
21   5  0.347363
22   6  0.170759
23   7  0.084413
你只需要这样:

ax.bar(np.arange(len(df)), df['y'])
ax.set_xticks(np.arange(len(df)))
ax.set_xticklabels(df['x'])

所以经过几次尝试,我发现了问题所在。我的问题是我想用不连续的轴单位(不是中断)来绘图,我想要的数字是底部的数字(从5到10,然后从1到4)

下面是@Julien帮助下的代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#generate data for 'x' column
list_x = [x for x in range(1, 11)]
arrX = np.asarray(list_x)

#generate data for 'y' column
list_y = [i for i in range(10, 110, 10)]
arrY = np.asarray(list_y)

#generate the dataframes
df1 = pd.DataFrame({'x': arrX, 'y': arrY})

df2 = pd.concat([df1[4:],df1[:4]])
df2 = df2.reset_index(drop=True)

print(df1)
print(df2)

fig = plt.figure(dpi=128, figsize=(6, 6))
ax1, ax2 = fig.add_subplot(211), fig.add_subplot(212)

ax1.bar(np.arange(len(df1)), df1['y'])
ax1.set_xticks(np.arange(len(df1)))
ax1.set_xticklabels(df1['x'])

ax2.bar(np.arange(len(df2)), df2['y'])
# ax2.bar(df2['x'], df2['y'])  ## this will not work. Has to use the code above

# @Julien provides the following to modify the label
ax2.set_xticks(np.arange(len(df2)))
ax2.set_xticklabels(df2['x'])


plt.show()

基本上有两种选择。(1) 通过绘制索引并将标签设置为移位的数字来伪造轴单位。(2) 真正改变轴单位。我不确定你想要的是什么。我认为第一个对我来说已经足够好了,我只想从中间开始单位(在这个例子中是8)我想我必须真正改变轴单位,只要改变标签的显示就会改变我的绘图。谢谢@朱利安,这对我很有用!但是我可以问一下为什么“ax.setxticklabels(df['x'])不起作用,并且必须添加行“ax.setxticks(np.arange(len(df))”?这是为了指定记号的位置。如果你不这样做,它将使用默认设置,这将把你搞砸。好的,现在就知道了。非常感谢你的解释~嗨,朱利安,我发现了一个问题。它只会更改x轴的显示,但不会真正更改绘图不确定您的意思。。。为什么要“改变情节”?