matplotlib 在seaborn catplot上设置xtick formatter会将x刻度的值更改为索引

3z6pesqy  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(152)

我试图用海运catplot来可视化一个简单的订单簿框架。然而,当我设置catplot的ax的x tick标签的格式时,它会将标签的值更改为索引(0-10而不是9.95-10.05)。我试过直接使用.barplot(),结果也一样。这是seaborn创建条形图的方式吗?我从来没有遇到过这个问题与线图。

book = pd.DataFrame({'price': np.arange(10.05, 9.95, -0.01), 'type': '?', 'qty': 0})
book.iloc[1, 2] = 1800
book.iloc[2, 2] = 500
book.iloc[3, 2] = 500
book.iloc[4, 2] = 100
book.iloc[0:6, 1] = 'Ask'

book.iloc[6, 2] = 100
book.iloc[7, 2] = 200
book.iloc[8, 2] = 600
book.iloc[9, 2] = 2500
book.iloc[6:11, 1] = 'Bid'

cat = sns.catplot(x='price', y='qty', data=book, hue='type', kind='bar') 
cat.tick_params(axis='x', rotation=45)

cat.ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f'{x:.2f}'))

xyhw6mcr

xyhw6mcr1#

Python seaborn分类条形图,带有自定义格式的x轴刻度标签

您需要将整数x轴索引转换回嵌套框中相应的price值。
例如,像这样:

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

book = pd.DataFrame(
    {"price": np.arange(9.95, 10.05, 0.01), "type": "?", "qty": 0}
)
book.iloc[1, 2] = 1800
book.iloc[2, 2] = 500
book.iloc[3, 2] = 500
book.iloc[4, 2] = 100
book.iloc[0:6, 1] = "Ask"

book.iloc[6, 2] = 100
book.iloc[7, 2] = 200
book.iloc[8, 2] = 600
book.iloc[9, 2] = 2500
book.iloc[6:11, 1] = "Bid"

fig, ax = plt.subplots(figsize=(6, 4), dpi=150)
sns.barplot(
    x="price",
    y="qty",
    data=book,
    hue="type",
    ax=ax,
    order=book["price"][::-1],
    dodge=False,
)

ax.set_xticks(range(len(book["price"])))
ax.set_xticklabels(book["price"].round(2), rotation=45)

ax.xaxis.set_major_formatter(
    ticker.FuncFormatter(lambda x, pos: f'${book["price"].iloc[x]:.2f}')
)

plt.tight_layout()
plt.show()

  • 注 *:我不能100%确定您提供的示例代码中是否存在错误,但是,奇怪的是,有必要更改价格范围(定义为np.arange),然后颠倒绘制数据的顺序,以获得与所提供的预期输出相匹配的图,并显示在问题中。

相关问题