如何将条形图值的格式设置为小数点后两位,仅适用于数据中存在的值?

2024-09-27 17:51:31 发布

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

我正在尝试使用searborn绘制水平条形图。但是我希望y轴显示数据的两个小数点,但是只显示数据中存在的值,,例如0.960.93

以下是我所拥有的:

df=pd.read_excel('file.xlsx', sheet_name='all')
print(df['digits'])

1.   0.96270
1    0.93870
2    0.93610
3    0.69610
4    0.61250
5    0.61280
6    0.52965
7    0.50520

sns.histplot(y=df['digits'])
plt.xlabel("frequency", fontsize=15)
plt.ylabel("results",fontsize=15)

这是输出

enter image description here


Tags: 数据dfread水平绘制pltxlsxexcel
3条回答

要创建一个直方图,其中四舍五入到2位小数的值定义了箱子,可以在这些值中间创建箱子边。例如0.1950.205处的箱子边缘将定义0.20周围的箱子。您可以使用'np.arange(-0.005,1.01,0.01)'创建具有这些容器边缘的数组

为了只在使用的位置设置记号标签,可以使用ax.set_yticks()。可以对所有y值进行舍入,并对y记号使用唯一的值

如果不需要舍入,而需要截断,可以使用bins=np.arange(0, 1.01, 0.01)ax.set_yticks(np.unique(np.round(y-0.005, 2)))

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import seaborn as sns

y = np.array([0.96270, 0.93870, 0.93610, 0.69610, 0.61250, 0.61280, 0.52965, 0.50520])

ax = sns.histplot(y=y, bins=np.arange(-0.005, 1.01, 0.01), color='crimson')
ax.set_yticks(np.unique(np.round(y, 2)))
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.tick_params(axis='y', labelsize=6)
ax.set_xlabel("frequency", fontsize=15)
ax.set_ylabel("results", fontsize=15)
plt.show()

请注意,即使字体大小较小,记号标签也可能重叠

histplot with only tick labels at nonzero positions

另一种方法是对舍入(或截断)的值使用countplot。然后,条间距均匀,不考虑空点:

y = np.array([0.96270, 0.93870, 0.93610, 0.69610, 0.61250, 0.61280, 0.52965, 0.50520])
y_rounded = [f'{yi:.2f}' for yi in sorted(y)]
# y_truncated = [f'{yi - .005:.2f}' for yi in sorted(y)]
ax = sns.countplot(y=y_rounded, color='dodgerblue')

ax.xaxis.set_major_locator(MaxNLocator(integer=True))

countplot for values rounded to 2 decimals

这由matplotlib处理:

ax = sns.histplot(y=np.random.randn(20))
ax.xaxis.set_major_formatter("{x:.2f}")
ax.set_xlabel("frequency", fontsize=15)
ax.set_ylabel("results",fontsize=15)

enter image description here

您可能需要使用以下选项:

import matplotlib.ticker as tkr

y = [0.96270, 0.93870, 0.93610, 0.69610, 0.61250, 0.61280, 0.52965, 0.50520]
g = sns.histplot(y=y)
plt.xlabel("frequency", fontsize=15)
plt.ylabel("results",fontsize=15)

g.axes.yaxis.set_major_formatter(tkr.FuncFormatter(lambda y, p: f'{y:.2f}'))

set_major_formatter

或者这个:

import matplotlib.ticker as tkr

y = [0.96270, 0.93870, 0.93610, 0.69610, 0.61250, 0.61280, 0.52965, 0.50520]
g = sns.histplot(y=y, binwidth=0.01)
plt.xlabel("frequency", fontsize=15)
plt.ylabel("results",fontsize=15)

g.axes.yaxis.set_major_formatter(tkr.FuncFormatter(lambda y, p: f'{y:.2f}'))

binwidth=0.01

binwidth=0.01

相关问题 更多 >

    热门问题