[英]Combine multiple columns in a dataframe for ggplot2 in R
我下面有一個數據框,我試圖繪制它,以便Red
、 Blue
、 Green
和MSAVI
下的值顯示在y-axis
而Red
、 Blue
、 Green
、 MSAVI
顯示在x-axis
。 圖例中顯示的class
值和color
也可以根據這些字符值定義。 下面是我嘗試使用ggplot2
在R
中ggplot2
。
我怎樣才能使用dplyr
做到這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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.