如何设置matplotlib x轴的起点?

2024-10-01 17:37:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用Seaborn/matplotlib时遇到了一个看似简单的问题,因为我的x轴值似乎与条形图上的标签没有正确关联。作为参考,我有一个pandas.DataFrame对象,并删除了前20行以显示对数据的更详细的查看,留给我的是类似于:

hypothesis1_df:

     revol_util  deviation
20           20 -37.978539
21           21 -27.313996
22           22 -23.790328
23           23 -19.729957
24           24 -16.115686
..          ...        ...
96           96  67.275585
97           97  91.489382
98           98  60.967792
99           99  48.385094
100         100  77.852812

现在的问题是,当我使用以下代码绘制此图时:

^{pr2}$

我明白了:

Image1

注意x轴的值以及它们不是从20开始的。有什么办法可以抵消股票价格吗?我尝试了ax.set_xlim(xmin=20, xmax=100),但这只会将图表的底部20切掉,并将其向右扩展到空白处。如果我删除所有的坐标轴格式,它的标签是正确的,但由于每个标签都列出来了,所以太忙了。谢谢你的帮助。在


Tags: 数据对象代码dataframepandasdfmatplotlibutil
3条回答

因为我们知道seaborn条形图中的刻度总是从0开始,所以我们只需将您的revol_util值的第一个值添加到^{}中的当前刻度上,同时添加现有的MultipleLocator。在

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# A fake dataframe
hypothesis1_df = pd.DataFrame({
    'revol_util':np.arange(20, 101, 1),
    'deviation':np.arange(-40, 81, 1.5) + np.random.rand(81)*10.})
hypothesis1_df = hypothesis1_df.set_index('revol_util', drop=False)

ax = sns.barplot(x='revol_util', y='deviation', data=hypothesis1_df)
ax.set(xlabel="Revolving Credit Utilization (%)",
           ylabel="Deviation from Mean (%)",
           title="Credit Utilization and Likelihood of Late Payments\n(20 - 100%)")

ax.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(
    lambda x, pos: '{:g}'.format(x + hypothesis1_df['revol_util'].iloc[0])))

plt.show()

enter image description here

问题是,在seaborn条形图中,条形图确实位于0,1,...,N-1;它们的标签用FixedLocator设置为与数据对应的数字。在

因此,一个选项可以: 使用多个定位器并手动设置勾选标签

    ax.xaxis.set_major_locator(ticker.MultipleLocator(10))
    ax.set_xticklabels(df.index.tolist()[::10]) # take every tenth label from list

尝试:ax.set_xticklabels(hypothesis1_df.index.tolist()) 手动设置x轴标签。在

相关问题 更多 >

    热门问题