Seaborn如何将xticks从float类型改为int类型

6

我正在使用seaborn作为sns和pylab作为plt来绘制图形:

plt.figure(figsize=(10,10),)
sns.barplot(y = 'whatever_y', x = 'whatever_x' , data=mydata)
plt.xticks(fontsize=14, fontweight='bold')

xticks应该是0, 1, 2, 3但是它们被绘制成了0.0,1.0,2.0,3.0。

有人知道我需要添加什么才能使它们变成整数吗?-(数据是pandas dataframe)谢谢


mydata是什么?它是一个numpy数组还是其他什么东西? - EdChum
3
使用 df['x_col_name'] = df['x_col_name'].astype(int) 可以更改列的数据类型为整数型。 - EdChum
谢谢,这个方法可行。那么这个问题是否仍未解决,或者在seaborn/pylab中有一种将xticks从浮点数转换为整数的方法? - Annamarie
是的,您可以操纵它们。我认为您需要在 ticker 上使用格式化程序,但我不是 matplotlib 专家。 - EdChum
好的,无论如何感谢您。我会把问题留在那里 - 也许有人知道在matplotlib中实现这个便捷技巧。 - Annamarie
5个回答

7

您可以使用轴格式化程序来完成:

from  matplotlib.ticker import FuncFormatter

然后,在您的条形图代码行之后:

plt.gca().xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))

2
这个指南展示了如何操作 facetgrid: https://seaborn.pydata.org/tutorial/axis_grids.html
with sns.axes_style("white"):
     g = sns.FacetGrid(tips, row="sex", col="smoker", margin_titles=True, height=2.5)
g.map(sns.scatterplot, "total_bill", "tip", color="#334488")
g.set_axis_labels("Total bill (US Dollars)", "Tip")
g.set(xticks=[10, 30, 50], yticks=[2, 6, 10])
g.fig.subplots_adjust(wspace=.02, hspace=.02)

行"g.set"使用xticks参数。 例如,我有一个带有整数1到18的pandas数据框列,显示为1.0等等。 我这样解决:

g.set(xticks=list(range(1,19)))

希望这对你有用。

1

很容易,使用MaxNLocator如下:

import seaborn as sns
from seaborn import displot 
import matplotlib.pyplot as plt


import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

y=[1, 0, 0, 1, 1, 1]
face_grid = sns.displot(y, color="aquamarine")
fig = face_grid.figure
ax = fig.gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

0

如果你正在使用 seaborn(在 jupyter notebook 中也适用),你也可以这样做。

from  matplotlib.ticker import FuncFormatter
ax = sns.barplot(x='x', y='y',hue='', data=data_set_pd)
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
plt.show()

-1
这里有一个直观的方法来修复 matplotlib 中的刻度:
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1))
plt.yticks(np.arange(min(y), max(y)+1, 1))

代码在 seaborn 图表之后的同一单元格中运行(在 jupyter notebook 中)。这是因为 seaborn 使用 matplotlib 后端。


这个问题涉及到seaborn,考虑在回答中提供解释。 - Algorithman
1
也许不是“上乘之选”,但Artur的东西很好用:x = df [“myvar1”] plt_plot = sns.relplot(x=x, y=“myvar2”, kind=“line”, data=df, ci=None, aspect=2) plt.xticks(np.arange(min(x), max(x)+1, 1)) - Nando

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接