【问题标题】:Format numbers on axes and tooltips in ggplotly在ggplotly中格式化轴和工具提示上的数字
【发布时间】:2020-04-16 17:44:15
【问题描述】:

我使用 sprintf 和 formatC 来获取一个双精度值并将其四舍五入到小数点后两位。但是,当我在 ggplot 和 ggplotly 中使用它时,它会让我的视觉效果表现出来。

输入:

   structure(list(Date = structure(c(18328, 18329, 18330, 18331, 
    18332, 18333), class = "Date"), State = c("Louisiana", "Louisiana", 
    "Louisiana", "Louisiana", "Louisiana", "Louisiana"), variablename1 = c(0, 
    0, 1, 1, 6, 14), variablename2 = c(5, 5, 5, 11, 37, 37), death = c(0, 
    0, 0, 0, 0, 0), variablename3 = c(5, 5, 6, 12, 43, 51), variablename4 = c(0, 
    0, 0, 0, 0, 0), variablename5 = c(0, 0, 0, 0, 0, 0), variablename6 = c(0, 
    0, 0, 6, 26, 0), variablename7 = c(0, 0, 1, 0, 5, 8), variablename8 = c(0, 
    5, 1, 6, 31, 8), Percent = c(0, 0, 16.6666666666667, 8.33333333333333, 
    13.953488372093, 27.4509803921569)), row.names = c(NA, -6L), groups = structure(list(
        State = "Louisiana", .rows = list(1:6)), row.names = c(NA, 
    -1L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
    "tbl_df", "tbl", "data.frame"))

编辑:在寻找技巧的过程中,我发现“非短”的做事方式更有效。只需使用 round(variable, 2) 将值四舍五入到小数点后第二位并使用它。暂时。

【问题讨论】:

  • 您能添加一个您的 ggplot 代码示例吗?我还看到您有多个名为variablename 的列。我猜你这样做是为了发布一个可用的数据集。但是,如果您要在 ggplot 中绘制它,它将不知道要引用哪一列,因为它们都被称为相同的。

标签: r ggplot2 r-plotly ggplotly


【解决方案1】:

这可以通过scales::percentscales::percent_format 轻松实现。例如,我用Date 绘制了Percent 的线图,其中我使用scales::percent_format 格式化y 轴标签,使用scales::percent 格式化工具提示中的百分比值:

library(ggplot2)
library(plotly)

p <- df %>% 
  ungroup() %>% 
  ggplot(aes(Date, Percent, color = State, group = State, 
             text = sprintf("State: %s<br>Date: %s<br>Percent: %s", 
                            State, Date, scales::percent(Percent, scale = 1, accuracy = .01)))) +
  geom_line() +
  scale_y_continuous(labels = scales::percent_format(scale = 1, accuracy = .01))

ggplotly(p, tooltip = 'text')

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多