簡體   English   中英

如何使用兩個 y 軸和一個 x 軸在布局中繪制多個圖形

[英]How to draw multiple graph in a layout using two y axises and one x axis

我想使用一種布局顯示時間、y_min、y_max 的圖形結果,按時間(X 軸)在 y 軸上繪制兩條線(min_value 和 max_value),並在 y 軸上繪制 min_value 和 max_value 的分離圖。

##Data Set(test.csv) X軸是時間 Y軸是y_min, y_max

時間 最小值 最大值
945 0.892021996 0.964050503
955 0.769454489 0.884603426
965 0.774495876 0.884901433
975 0.745542623 0.897309432
985 0.753567721 0.912993446
  '''code'''
  Plot_graph = ggplot(.,aes(x=time, y=...))+geom_line(aes(group=Value, color=Value))+ geom_smooth(method="auto",aes(group=Value,color=Value))+ scale_colour_manual(values = c("red","blue"))+ scale_x_continuous(breaks=0:8000*1000,limits=c(time_min,time_max)) + scale_y_continuous(breaks=0:8000*0.1,limits=c(min_value,max_value)) + theme_classic()+labs(subtitle = "B. Original data (mean, min, max values)")

這段代碼有問題。

讓我知道如何使用兩個 y 軸和一個 x 軸在布局中繪制多個圖形。

你有兩種方法可以做到——一種簡單,另一種更整潔。

簡單的方法是進行兩次geom_line調用並為每個調用更改aes(y= ) (手動設置顏色):

library(ggplot2)
library(tidyr)

df <- dplyr::tribble(~time, ~min_value,   ~max_value,
                      945,  0.892021996,    0.964050503,
                      955,  0.769454489,    0.884603426,
                      965,  0.774495876,    0.884901433,
                      975,  0.745542623,    0.897309432,
                      985,  0.753567721,    0.912993446)

ggplot(df, aes(x = time)) +
  geom_line(aes(y = min_value), colour = "red") +
  geom_line(aes(y = max_value), colour = "blue")

一個整潔的方法是將 pivot 您的表作為變量的測量名稱:


df %>% pivot_longer(-time) %>% 
  ggplot(aes(time, value, colour = name)) +
  geom_line() +
  scale_colour_manual(values = c("red","blue"))

代表 package (v1.0.0) 於 2021 年 3 月 24 日創建

基本解決方案的一種可能性是,首先繪制假設min_value的線,然后使用lines()添加第二個max_value

所以這看起來像:

plot(test.csv$time, test.csv$min_value, type = "l") 
lines(test.csv$time, test.csv$max_value)

對於ggplot版本,您需要將 dataframe 轉換為長格式:

test.csv <- melt(test.csv, id.vars = "time")
ggplot(test.csv, mapping = aes(x = variable, y = value, col = time)) +
geom_line()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM