如何使用两个 y 轴和一个 x 轴在布局中绘制多个图形

时间:2021-03-24 21:26:07

标签: r ggplot2

我想使用一种布局显示时间、y_min、y_max 的图形结果,按时间(X 轴)在 y 轴上绘制两条线(最小值和最大值),并在 y 轴上绘制 min_value 和 max_value 的分离图。< /p>

##数据集(test.csv) X轴是时间 Y 轴为 y_min, y_max

<头>
时间 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
  '''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 轴在布局中绘制多个图形。

2 个答案:

答案 0 :(得分:1)

你有两种方法可以做到——一种简单,另一种更整洁。

简单的方法是调用两个 Sub CheckSelection() Dim s As String, i As Long, sep For i = 1 To 6 With Me.Controls("Checkbox" & i) If .Value = True Then s = s & sep & .Tag 'ranges are stored in checkboxes' Tag property sep = "," End If End With Next i If Len(s) = 0 Then s = "A1" 'default selection if none chosen... ActiveSheet.Range(s).Select Debug.Print s End Sub Private Sub CheckBox1_Click() CheckSelection End Sub '... ' etc '... Private Sub CheckBox6_Click() CheckSelection End Sub 并为每个调用更改 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")

reprex package (v1.0.0) 于 2021 年 3 月 24 日创建

答案 1 :(得分:0)

基本解决方案的一种可能性是,首先绘制假设 min_value 的线,然后使用 max_value

添加第二个 lines()

所以这看起来像:

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

对于 ggplot 版本,您需要将数据帧转换为长格式:

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