【问题标题】:Different axis label format depending on value using plotly不同的轴标签格式取决于使用 plotly 的值
【发布时间】:2022-01-01 08:20:07
【问题描述】:

我有一个情节,我希望将值 >= 0 格式化为百分比,将值 ggplot 和plotly 来实现这一点,如下所示:

library(tidyverse)
library(plotly)

df <- data.frame(x = -5:5,
                 y = 0:10) 

p1 <- df %>% 
  ggplot(aes(x = x, y = y)) +
  geom_point() +
  scale_x_continuous(labels = function(x) paste0(x, ifelse(x >= 0, "%", "")))

ggplotly(p1)

但是,我想使用本机 plotly 语法而不使用 ggplotly 包装器来完成这一切。谁能告诉我该怎么做?

df %>% 
  plot_ly %>% 
  add_markers(x = ~x,
              y = ~y)

【问题讨论】:

    标签: r ggplot2 plotly


    【解决方案1】:

    一种选择是获取所需中断的向量,并通过layout 设置这些中断和标签,如下所示:

    注意:对于休息时间,我使用 scales::breaks_extended()(range(df$x)),它为我们提供了 scale_x_continuous 使用的默认休息时间。

    library(plotly)
    
    df <- data.frame(x = -5:5,
                     y = 0:10)
    
    breaks_x <- scales::breaks_extended()(range(df$x))
    
    df %>% 
      plot_ly() %>% 
      add_markers(x = ~x,
                  y = ~y) %>% 
      layout(xaxis = list(
        ticktext = paste0(breaks_x, ifelse(breaks_x >= 0, "%", "")), 
        tickvals = breaks_x,
        tickmode = "array"
      ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2023-04-09
      • 1970-01-01
      • 2021-04-18
      • 2017-05-10
      相关资源
      最近更新 更多