我有以下代码:
library(tidyverse)
library(dplyr)
df <- tibble(a = c(1,2,3,4,5,6,7,8), b = c(10, 20 , 30, 40, 50, 60, 70, 80), c = c(4, 5, 6, 34, 5, 22, 12, 45), d = c(1,2,3, 3, 3, 2, 1, 1))
df <- df %>%
mutate(Type = case_when(d <= 1 ~ 'A',
d <= 2 ~ 'B',
d > 2 ~ 'C'))
df
# A tibble: 8 x 5
a b c d Type
<dbl> <dbl> <dbl> <dbl> <chr>
1 1 10 4 1 A
2 2 20 5 2 B
3 3 30 6 3 C
4 4 40 34 3 C
5 5 50 5 3 C
6 6 60 22 2 B
7 7 70 12 1 A
8 8 80 45 1 A
我想绘制一个条形图,其中每种类型都应具有3个值(a,b,c列)。
我的问题是如何显示三个不同的y轴值。
我想要这样的东西:
它将并排放置A,B和C盒(在图像中只有A)。
问题在于如何显示这三个值。
答案 0 :(得分:1)
那呢:
library(reshape2)
library(tidyverse)
df %>%
group_by(Type) %>% # group by
summarise_all(sum) %>% # function that summarise the numbers: you can use mean or whatever you want
reshape2::melt() %>% # from wide to long format
ggplot(aes(x = variable, y = value)) + # now plot it!
geom_bar(stat ='identity') +
facet_wrap(vars(Type))
答案 1 :(得分:1)
如果您要使用名为cowplot
的很酷的软件包。
library(tidyverse)
library(cowplot)
d <- df %>%
select(-d) %>% # remove variable "d"
group_by(Type) %>% # group by Type
summarise_all(sum) %>% # sum all columns values for each Type
gather("x","y",-Type) %>% # Transform the data in x(variable) and y(count) for each Type
nest(-Type) %>% # Nest by Type
rowwise() %>% # Apply transformations by line
mutate(plot = list(ggplot(data,aes(x = x, y = y)) +
geom_bar(stat ='identity') +
theme_bw() +
labs(title = Type) +
ylab("Value") +
xlab("") +
theme(plot.title = element_text(hjust = .5))))
# plot the charts side by side using cowplot
plot_grid(plotlist = d$plot,nrow = 1)