在Matplotlib绘图中将轴的范围更改为非连续数

时间:2018-11-09 00:19:06

标签: 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.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

2 个答案:

答案 0 :(得分:1)

您只需要这个:

{{template $MyVar}}

答案 1 :(得分:0)

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

enter image description here

以下是@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()