对图箱形图的四分位数中的数字进行舍入

发布于 2025-01-15 04:51:54 字数 802 浏览 1 评论 0原文

我已经研究了一段时间,试图弄清楚如何对悬停功能中显示的四分位数中显示的数字进行四舍五入。必须有一个简单的方法来执行此操作,就像使用 x 和 y 坐标一样。在这种情况下,四舍五入到小数点后两位就足够了。

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/tips.csv")

fig = go.Figure(data=go.Box(y=df['total_bill'],
                            name='total_bill',
                            boxmean=True,
                           )
               )

fig.update_layout(width=800, height=800,
                  hoverlabel=dict(bgcolor="white",
                                  font_size=16,
                                  font_family="Arial",
                                 )
                 )
fig.show()

输入图片此处描述

I have been digging around a while trying to figure out how to round the numbers displayed in quartile figures displayed in the hover feature. There must be a straightforward to do this as it is with the x and y coordinates. In this case rounding to two decimals would be sufficient.

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/tips.csv")

fig = go.Figure(data=go.Box(y=df['total_bill'],
                            name='total_bill',
                            boxmean=True,
                           )
               )

fig.update_layout(width=800, height=800,
                  hoverlabel=dict(bgcolor="white",
                                  font_size=16,
                                  font_family="Arial",
                                 )
                 )
fig.show()

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸短情长 2025-01-22 04:51:54

不幸的是,这看起来 Plotly 无法轻易做到。如果您修改hovertemplate,它将仅适用于您将鼠标悬停在其上的标记(异常值),并且每个箱线图统计数据后面的小数在悬停时将保持不变。 plotly-python 的另一个问题是您无法提取箱线图统计信息,因为这需要您与底层的 javascript 进行交互。

但是,您可以使用与绘图相同的方法自行计算箱线图统计数据,并将所有统计数据四舍五入到小数点后两位。然后,您可以传递箱线图统计数据:lowerfence, q1,median,mean, q3, upperfence强制plotly手动构建箱线图,并将所有异常值绘制为另一条散点图。

这是一个相当难看的黑客行为,因为您实际上是在重做 Plotly 已经执行的所有计算,然后手动构建箱线图,但它确实强制箱线图统计数据显示到小数点后两位。

from math import floor, ceil
from numpy import mean
import pandas as pd
import plotly.graph_objects as go

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/tips.csv")

## calculate quartiles as outlined in the plotly documentation 
def get_percentile(data, p):
    data.sort()
    n = len(data)
    x = n*p + 0.5
    x1, x2 = floor(x), ceil(x)
    y1, y2 = data[x1-1], data[x2-1] # account for zero-indexing
    return round(y1 + ((x - x1) / (x2 - x1))*(y2 - y1), 2)

## calculate all boxplot statistics
y = df['total_bill'].values
lowerfence = min(y)
q1, median, q3 = get_percentile(y, 0.25), get_percentile(y, 0.50), get_percentile(y, 0.75)
upperfence = max([y0 for y0 in y if y0 < (q3 + 1.5*(q3-q1))])

## construct the boxplot
fig = go.Figure(data=go.Box(
    x=["total_bill"]*len(y),
    q1=[q1], median=[median], mean=[round(mean(y),2)],
    q3=[q3], lowerfence=[lowerfence],
    upperfence=[upperfence], orientation='v', showlegend=False,
    )
)

outliers = y[y>upperfence]
fig.add_trace(go.Scatter(x=["total_bill"]*len(outliers), y=outliers, showlegend=False, mode='markers', marker={'color':'#1f77b4'}))
               

fig.update_layout(width=800, height=800,
                  hoverlabel=dict(bgcolor="white",
                                  font_size=16,
                                  font_family="Arial",
                                 )
                 )

fig.show()

输入图片此处描述

Unfortunately this is something that it looks like Plotly cannot easily do. If you modify the hovertemplate, it will only apply to markers that you hover over (the outliers), and the decimals after each of the boxplot statistics will remain unchanged upon hovering. Another issue with plotly-python is that you cannot extract the boxplot statistics because this would require you to interact with the javascript under the hood.

However, you can calculate the boxplot statistics on your own using the same method as plotly and round all of the statistics down to two decimal places. Then you can pass boxplot statistics: lowerfence, q1, median, mean, q3, upperfence to force plotly to construct the boxplot manually, and plot all the outliers as another trace of scatters.

This is a pretty ugly hack because you are essentially redoing all of calculations Plotly already does, and then constructing the boxplot manually, but it does force the boxplot statistics to display to two decimal places.

from math import floor, ceil
from numpy import mean
import pandas as pd
import plotly.graph_objects as go

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/tips.csv")

## calculate quartiles as outlined in the plotly documentation 
def get_percentile(data, p):
    data.sort()
    n = len(data)
    x = n*p + 0.5
    x1, x2 = floor(x), ceil(x)
    y1, y2 = data[x1-1], data[x2-1] # account for zero-indexing
    return round(y1 + ((x - x1) / (x2 - x1))*(y2 - y1), 2)

## calculate all boxplot statistics
y = df['total_bill'].values
lowerfence = min(y)
q1, median, q3 = get_percentile(y, 0.25), get_percentile(y, 0.50), get_percentile(y, 0.75)
upperfence = max([y0 for y0 in y if y0 < (q3 + 1.5*(q3-q1))])

## construct the boxplot
fig = go.Figure(data=go.Box(
    x=["total_bill"]*len(y),
    q1=[q1], median=[median], mean=[round(mean(y),2)],
    q3=[q3], lowerfence=[lowerfence],
    upperfence=[upperfence], orientation='v', showlegend=False,
    )
)

outliers = y[y>upperfence]
fig.add_trace(go.Scatter(x=["total_bill"]*len(outliers), y=outliers, showlegend=False, mode='markers', marker={'color':'#1f77b4'}))
               

fig.update_layout(width=800, height=800,
                  hoverlabel=dict(bgcolor="white",
                                  font_size=16,
                                  font_family="Arial",
                                 )
                 )

fig.show()

enter image description here

小镇女孩 2025-01-22 04:51:54

对我来说,设置 yaxis_tickformat=",.2f" 有效:

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/tips.csv")

fig = go.Figure(data=go.Box(y=df['total_bill'],
                            name='total_bill',
                            boxmean=True,
                           )
               )

fig.update_layout(width=800, height=800,
                  # >>>>
                  yaxis_tickformat=",.2f",
                  # <<<<
                  hoverlabel=dict(bgcolor="white",
                                  font_size=16,
                                  font_family="Arial",
                                 )
                 )
fig.show()

...您还可以通过设置 y 刻度的文本来覆盖 yaxis:

fig.update_layout(
 yaxis = dict(
   tickformat=",.2f",
   tickmode = 'array',
   tickvals = [10, 20, 30, 40, 50],
   ticktext =["10", "20", "30", "40", "50"],
))

如果您希望 y 轴刻度保持不变
(在图 5.8.2 上测试)

for me, setting yaxis_tickformat=",.2f" worked:

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/tips.csv")

fig = go.Figure(data=go.Box(y=df['total_bill'],
                            name='total_bill',
                            boxmean=True,
                           )
               )

fig.update_layout(width=800, height=800,
                  # >>>>
                  yaxis_tickformat=",.2f",
                  # <<<<
                  hoverlabel=dict(bgcolor="white",
                                  font_size=16,
                                  font_family="Arial",
                                 )
                 )
fig.show()

... you can also override yaxis back by setting text of y ticks:

fig.update_layout(
 yaxis = dict(
   tickformat=",.2f",
   tickmode = 'array',
   tickvals = [10, 20, 30, 40, 50],
   ticktext =["10", "20", "30", "40", "50"],
))

if you want the y axis ticks unchanged
(tested on plotly 5.8.2)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文