ggplot2反转辅助y轴

时间:2019-07-26 10:40:47

标签: r ggplot2

graph example

我正在创建一个图形,在得分的主要y轴(缩放比例为0-5)和次要y轴PCR结果(缩放比例为0-45)上显示两个折线图。但是,我需要反转第二个y轴,以使45位于y轴的底部(45 =阴性PCR结果)。我可以绘制次要y轴,但不知道如何反转它。

链接到一些虚拟数据

https://www.filehosting.org/file/details/813109/redditexample.csv

library(data.table)
library(ggplot2)
library(lubridate)

#Read the file you want to use for a graph
data <- fread("redditexample.csv", na.strings = c("", NA))
data$V1 <- lubridate::dmy(data$V1)

plot <- ggplot(data) +
        geom_line(aes(x = V1, y = AveScore, col = type)) +
        geom_point(aes(x = V1, y = PCR)) +
        scale_y_continuous('PCR', sec.axis = sec_axis(trans = "reverse")

也尝试过:

scale_y_continuous('PCR', sec.axis = sec_axis(~ . *-1 + 50))

1 个答案:

答案 0 :(得分:0)

关键是要转换第二个y轴变量以生成图形,然后将其转换回以进行标记。使用您的数据,我使用以下代码生成了图形:

library(tidyverse)
ggplot(data) +
geom_line(aes(x = V1, y = AveScore, col = type)) +
geom_point(aes(x = V1, y = (50-PCR)/10)) +
scale_y_continuous('AveScore', sec.axis = sec_axis(~ 50 - .*10, name = "PCR"))                    

enter image description here

相关问题