[英]Adjust the values of secondary y axis in ggplot2 R
我正在嘗試使用兩個 y 軸 plot 數據。
p <- ggplot(mydf, aes(x = pos)) +
geom_line(aes(y = data1, colour="data1")) +
geom_line(aes(y = data2, colour="data2")) +
scale_y_continuous(limits = c(0.40, 0.90), breaks=c(0.40, 0.050, 0.60, 0.70, 0.80, 0.90), sec.axis = sec_axis(~., name = "data1")) +
labs(y = "freq",
x = "position",
colour = "") +
scale_colour_hue(labels = c("data1",
"data2"),
l = 40) +
ggtitle("title of the plot") +
theme_bw() +
theme(text=element_text(size=8)) +
theme(plot.title = element_text(hjust = 0.5, size =8)) +
theme(legend.direction = "horizontal", legend.position = "bottom", legend.box = "vertical")
plot(p)
第一個 y 軸值范圍為0.40-0.90
,第二個 y 軸值范圍為0.50-0.60
。 如何調整 plot?
pos data1 data2
1 0.9 0.6
2 0.8 0.6
3 0.8 0.6
4 0.7 0.6
5 0.6 0.5
6 0.5 0.5
7 0.4 0.5
mydf <- structure(list(win_mid = 88:97, emboss = c(0.8189, 0.81395, 0.818533333333333,
0.820825, 0.81846, 0.816883333333333, 0.815757142857143, 0.8149125,
0.814255555555556, 0.81373), clc = c(0.5985568621, 0.5985568621,
0.598507734833333, 0.59852001665, 0.59852738574, 0.5986134848,
0.598590549371429, 0.598623096925, 0.598573214244444, 0.59846694016
)), row.names = 76:85, class = "data.frame")
在ggplot2
上繪制輔助 y 軸與其說是繪圖問題,不如說是一個數學問題。 一般來說,我們需要取一組值並將它們擬合在最小值和最大值之間。 該答案具有通用公式https://stackoverflow.com/a/5295202/3962914在這種情況下可以實現為 -
library(ggplot2)
ggplot(mydf, aes(x = pos)) +
geom_line(aes(y = data1, colour="data1")) +
geom_line(aes(y = data2, colour="data2")) +
scale_y_continuous(limits = c(0.40, 0.90),
breaks=c(0.40, 0.050, 0.60, 0.70, 0.80, 0.90),
sec.axis = sec_axis(~{
a <- min(mydf$data2)
b <- max(mydf$data2)
(((b-a) * (. - min(.)))/diff(range(.))) + a
}, name = "data1")) +
labs(y = "freq",
x = "position",
colour = "") +
scale_colour_hue(labels = c("data1","data2"),
l = 40) +
ggtitle("title of the plot") +
theme_bw() +
theme(text=element_text(size=8)) +
theme(plot.title = element_text(hjust = 0.5, size =8)) +
theme(legend.direction = "horizontal",
legend.position = "bottom",
legend.box = "vertical")
在dput
數據上:
ggplot(mydf, aes(x = win_mid)) +
geom_line(aes(y = emboss, colour="emboss")) +
geom_line(aes(y = clc, colour="clc")) +
scale_y_continuous(limits = c(0.40, 0.90),
breaks=c(0.40, 0.050, 0.60, 0.70, 0.80, 0.90),
sec.axis = sec_axis(~{
a <- min(mydf$clc)
b <- max(mydf$clc)
(((b-a) * (. - min(.)))/diff(range(.))) + a
}, name = "emboss")) +
labs(y = "freq",
x = "position",
colour = "") +
scale_colour_hue(labels = c("emboss","clc"),
l = 40) +
ggtitle("title of the plot") +
theme_bw() +
theme(text=element_text(size=8)) +
theme(plot.title = element_text(hjust = 0.5, size =8)) +
theme(legend.direction = "horizontal",
legend.position = "bottom",
legend.box = "vertical")
數據
mydf <- structure(list(pos = 1:7, data1 = c(0.9, 0.8, 0.8, 0.7, 0.6,
0.5, 0.4), data2 = c(0.6, 0.6, 0.6, 0.6, 0.5, 0.5, 0.5)),
class = "data.frame", row.names = c(NA, -7L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.