r - 在 R 中为 ggplot2 组合数据框中的多列
问题描述
我在下面有一个数据框,我正在尝试绘制这样的值,以使 , 和 下Red
的Blue
值Green
显示MSAVI
在y-axis
和Red
, Blue
, Green
,MSAVI
上x-axis
。并且class
图例中显示的值color
也可以根据这些字符值进行定义。下面是我在R
使用ggplot2
.
我怎样才能做到这一点dplyr
?
Class Red Blue Green MSAVI
GRND 0.254241894 0.110313222 0.159854318 -0.216356573
SHRB 0.081104881 0.042177001 0.069155373 0.127747396
TREE 0.092559343 0.050581477 0.083049583 0.08810719
WATR 0.09050273 0.034529627 0.060246605 -0.182429743
dput(profiles)
structure(list(Class = structure(1:4, .Label = c("GRND",
"SHRB", "TREE", "WATR"), class = "factor"), Red = c(0.254241893688838,
0.081104880819718, 0.0925593425830205, 0.0905027302602927), Blue = c(0.110313221812248,
0.0421770010143518, 0.050581476961573, 0.034529626990358), Green = c(0.159854317704837,
0.0691553726792336, 0.0830495829383532, 0.0602466048051914),
MSAVI = c(-0.216356573005517, 0.12774739585196,
0.0881071899784729, -0.182429743309816)), row.names = c(NA,
-4L), class = "data.frame")
library(tidyverse)
# Read data
profiles = read.csv("~/profiles.csv)
# Plot using ggplot
profiles %>%
gather() %>%
ggplot(data = ., aes(x = fct_relevel(as.factor(key),
levels = c("Red",
"Blue",
"Green",
"MSAVI")), y = value,
group=Class, color = Class)) +
geom_point(size = 2.5) +
geom_line(lwd = 1.2) +
scale_color_manual(values=c('cyan', 'burlywood', 'darkgreen', 'blue')) +
labs(title = "Spectral Profile from Multispectral Imagery",
x = "Bands",
y = "Reflectance") +
#scale_y_continuous(limits=c(5000, 15000)) +
theme(panel.background = element_blank(),
panel.grid.major = element_line(color = "gray", size = 0.5),
panel.grid.minor = element_line(color = "gray", size = 0.5),
axis.ticks = element_blank())
解决方案
在这种情况下,您要使用pivot_longer
来组合data.frame
.
data %>% pivot_longer(
cols = -"Class"
)
它为您提供了一个长格式data.frame
,该格式收集了所有colums
定义在cols
. 在这种情况下,我使用negate
了,这样它结合了所有不是的列Class
,它给出了,
# A tibble: 16 x 3
Class name value
<fct> <chr> <dbl>
1 GRND Red 0.254
2 GRND Blue 0.110
3 GRND Green 0.160
4 GRND MSAVI -0.216
5 SHRB Red 0.0811
6 SHRB Blue 0.0422
7 SHRB Green 0.0692
8 SHRB MSAVI 0.128
9 TREE Red 0.0926
10 TREE Blue 0.0506
11 TREE Green 0.0830
12 TREE MSAVI 0.0881
13 WATR Red 0.0905
14 WATR Blue 0.0345
15 WATR Green 0.0602
16 WATR MSAVI -0.182
默认情况下,旋转的值进入value
,列进入name
。
data %>% pivot_longer(
cols = -"Class"
) %>% ggplot(
mapping = aes(x = name, y = value, color = Class, group = Class)
) + geom_line() + geom_point()
推荐阅读
- swiper - 当我添加一个以上的滑动元素时的奇怪行为
- javascript - 使用 vs 代码扩展进行调试时 test.js 中的 ES6 导入/导出失败并显示“SyntaxError:无法在模块外使用导入语句”
- firebase - Firebase 部署错误:必须在每个“托管”配置中使用“公共”提供公共目录
- react-native - React Native + React Navigation v5 - 在两个堆栈之间发送参数适用于模拟器,但不适用于真实设备
- javascript - 执行复制后从 arr 中删除特定键
- c++ - 错误:(E112)获取接口失败:端口未绑定:端口'server.outgoin1'(sc_out)
- python - Django 克隆递归对象
- javascript - getItem 时出现 aws DynamoDB 问题
- lua - 获取 TextBox 数据并对其进行操作时出错 - 已关闭 -
- bash - 在特定字符串之后注释字符串的第一个实例