R语言 对数刻度为零的曲线图

zour9fqk  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(168)

有没有人知道如何处理对数刻度的折线图,在那里plotly中有零值?线条就这样消失了。

library(tidyverse)
library(lubridate)
library(plotly)

df2 <- tibble::tribble(
  ~SAMPLE_DATE, ~REPORT_RESULT_VALUE,
  "2018-10-04",                 0.05,
  "2019-05-05",                 0.01,
  "2019-10-04",                    0,
  "2020-06-05",                 0.01,
  "2020-09-11",                    0,
  "2021-04-23",                    0,
  "2022-05-08",                 0.06 ) %>% 
  mutate(SAMPLE_DATE = ymd(SAMPLE_DATE))

plot_ly(data = df2) %>%
  add_trace(x = ~SAMPLE_DATE,
            y = ~REPORT_RESULT_VALUE,
            mode = "lines+markers") %>%
  layout(xaxis = list(title = 'Sample date'),
         yaxis = list(title = "Concentration (mg/L)",
                      type = "log"))

不久前我在plotly论坛上发现了一个类似的帖子,但没有解决方案:https://community.plotly.com/t/line-chart-with-zero-in-logarithmic-scale/40084

wfauudbj

wfauudbj1#

删除零对您有用吗?

plot_ly(data = df2 %>% filter(REPORT_RESULT_VALUE > 0)) %>%
  add_trace(x = ~SAMPLE_DATE,
            y = ~REPORT_RESULT_VALUE,
            mode = "lines+markers",
            na.rm = TRUE) %>%
  layout(xaxis = list(title = 'Sample date'),
         yaxis = list(title = "Concentration (mg/L)",
                      type = "log"))

创建于2022年12月22日,使用reprex v2.0.2

wfveoks0

wfveoks02#

这里有一种在ggplot2中使用方便的scales::pseudo_log_trans函数,然后使用plotly::ggplotly转换为plotly的方法。当您想要(主要是)对数刻度,但又想容纳零甚至负值时,pseudo_log_trans非常方便。

ggplotly(
  ggplot(df2, aes(SAMPLE_DATE, REPORT_RESULT_VALUE)) +
  geom_line() +
  geom_point() +
  scale_y_continuous(trans = scales::pseudo_log_trans(sigma = 0.005),
                     breaks = scales::breaks_pretty(n=10)) + # EDIT
  labs(x = 'Sample date', y = "Concentration (mg/L)")


相关问题