在Plotly中将坐标轴刻度标签格式化为百分比

26

我正在使用plotly创建柱状图,其中y轴表示0-1内的百分比或份额。 y轴显示为0.05而不是5.0%。

有没有办法将y轴刻度标签显示为%##

我尝试使用tickformat = "%"但似乎不起作用。


1
scale_y_continuous(labels = scales::percent_format()) 这个代码是否有效?(我假设您正在使用ggplot2,如果您没有发布可重现的示例,则很难确定)。 - RobertMyles
tickformat = "%" 是有效的。我写的函数中有一个错误。这个可以工作:layout(yaxis = list(title = "", tickformat = "%"), xaxis = list(title = ""), barmode = 'group') - Binny
2个回答

53

您可以在 plotly 中使用 layout 来实现此操作:

p <- p %>% 
          layout(yaxis = list(tickformat = "%"))

如果您只想添加%而不重新格式化数字,则可以使用以下方式:

p <- p %>% 
          layout(yaxis = list(ticksuffix = "%"))

示例:

这是一个示例,展示如何根据需要编辑y轴刻度(以下是图表中使用的数据)。

我有以下代码和图表:

plot_ly(z = eegmean$value, x = eegmean$xproj, y= eegmean$yproj, 
        type = "contour") %>% 
    layout(yaxis = list(range = c(0, 1)))

这里输入图片描述

我进行如下修改,得到了期望的输出:

plot_ly(z = eegmean$value, x = eegmean$xproj, y= eegmean$yproj*100, 
        type = "contour") %>% 
  layout(yaxis = list(ticksuffix = "%",  range = c(0, 100)))

这里输入图片描述

数据:

eegmean <-    
          structure(list(xproj = c(-4.36892281283989, 4.35956894475236, 
-3.66712823067503, 3.66912002532953, -6.74087785458615, 6.7287326256584, 
-3.06883681930631, 3.0727815538517, -3.05334720378955, 3.0570879596344, 
-3.79278629306119, 3.79086730312228, -7.07653326595358, 7.06235689946147, 
-7.90472265899708, 7.886291820964), yproj = c(0.0590663494057822, 
0.0624572214558794, 4.86096691858553, 4.85057791325599, 5.19791938823655, 
5.18984777332146, 9.40308855517187, 9.39510236056629, -9.35605694441838, 
-9.34632728162916, -4.81178659276704, -4.80386416586077, -5.3889955653921, 
-5.37981449730605, -0.00583969391994209, -0.00704057111565196
), value = c(0.0606980290462218, 0.0608382874925463, 0.0517195368020531, 
0.0531772440361526, 0.0204264049886253, 0.0177325467223879, 0.0392064861131087, 
0.0425640060844722, 0.0788962178010734, 0.0740093285228833, 0.0749098131481143, 
0.0759725415557911, 0.0688015959610801, 0.0762816652838652, 0.0548817124454006, 
0.0646901969995537)), .Names = c("xproj", "yproj", "value"), row.names = c("C3", 
"C4", "F3", "F4", "F7", "F8", "FP1", "FP2", "O1", "O2", "P3", 
"P4", "P7", "P8", "T7", "T8"), class = "data.frame")

4
如果您想显示百分比,请使用 tickformat = ".0%"。关于d3格式的详细文档可以在 mbostock 编写的这里找到。 - Bảo Trần

22

plotly文档指引我们到这个页面,该页面列出了所有可用的格式选项。

在此情况下,如5%的百分比,使用tickformat='%'即可。如果您还想显示小数点,则类似'.n%'的格式可以实现(将n替换为小数点后所需的位数)。

上述引用的 GitHub 页面包含更多格式选项。干杯!


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