Pandas 情节 - 无法设置 xticks

问题描述 投票:0回答:1

我正在尝试使用 pandas 数据框绘图方法绘制堆积条形图。 x 值是浮点数,我尝试以整数间隔设置 xticks 但没有成功。这是我的代码

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

data = [[0.0, 4.9, 19.9, 8.1, 0.0], [0.12, 4.5, 27.0, 10.1, 0.0], 
        [0.24, 2.8, 9.3, 4.6, 0.0], [0.36, 2.2, 9.1, 2.7, 0.0], 
        [0.48, 2.2, 7.3, 3.1, 0.0], [1.0, 4.9, 26.4, 11.2, 0.0], 
        [1.12, 5.9, 25.3, 8.7, 0.0], [1.24, 3.7, 13.3, 7.1, 0.0], 
        [1.3599999999999999, 3.0, 9.5, 3.4, 0.0], [1.48, 3.2, 8.9, 4.7, 0.0], 
        [2.0, 8.4, 24.8, 20.2, 0.0], [2.12, 9.5, 19.3, 22.5, 0.0], 
        [2.24, 5.7, 11.8, 6.6, 0.0], [2.36, 4.1, 11.1, 5.1, 0.0], 
        [2.48, 5.4, 8.0, 4.6, 0.0]]
df = pd.DataFrame(columns = ['xval', 'y1', 'y2', 'y3', 'y4'], data = data)
fig, ax = plt.subplots()
df.plot(x = 'xval', kind = 'bar', ax = ax, stacked = True)
xticks = [x for x in df['xval'] if int(x) == x]
ticklabel = ['{:.1f}'.format(x) for x in xticks]
ax.set_xticks(xticks, labels = ticklabel)
ax.grid()
fig.savefig('mychart.png')

enter image description here

pandas matplotlib xticks
1个回答
0
投票

您需要修复列表理解以考虑

xval
列的长度而不是列中的值:

xticks = [x for x in range(0,len(df['xval']))]

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.