Reputation: 1829
I have a dataset with 3 sets distribution each with 100 observation, I would like to plot these using ggplot posterior plot.
Data:
Name Value
A1 1
A1 1.2
A1 0.5
A2 5
A2 3
A2 -1
A3 5
A3 2
A3 1
Problem:
I am unable to sort the value by the mean value, the expected result should be "A2, A3, A1" in the plot.
Attempted solution:
ggplot(value1, aes(reorder(mean(value)), x = value, y = name))+
geom_posterior() +
xlab("value") + theme_bw()
Full Code with Data:
library("tidyverse")
library("ggdistribute") #plot geom_posterior
value1 <- rnorm(n=100, mean=1, sd=1) %>% as.data.frame()
value2 <- rnorm(n=100, mean=3, sd=1) %>% as.data.frame()
value3 <- rnorm(n=100, mean=1, sd=2) %>% as.data.frame()
value1$name <- "A1"
value2$name <- "A2"
value3$name <- "A3"
value1 <- rbind(value1,value2,value3)
colnames(value1) <- c("value","name")
ggplot(value1, aes(reorder(mean(value)), x = value, y = name))+
geom_posterior() +
xlab("value") + theme_bw()
Upvotes: 0
Views: 62
Reputation: 1252
This may be a bit of a workaround - if you change name to an ordered factor and provide the levels in the order you'd like the graphs to be shown, then ggplot uses the factor levels for ordering:
my_levels <- value1 %>%
group_by(name) %>%
summarize(mean = mean(value)) %>%
arrange(mean) %>%
select(name)
value1$name <-factor(value1$name, levels = my_levels$name, ordered = TRUE)
ggplot(value1, aes(reorder(mean(value)), x = value, y = name))+
geom_posterior() +
xlab("value") + theme_bw()
Upvotes: 1
Reputation: 30559
You can reorder by mean:
reorder(name, value, mean)
specifying the vector whose levels will be reordered, a vector whose subset of values determines the order, and a function to apply to subsets (in this case, mean
).
library(tidyverse)
library(ggdistribute)
set.seed(123)
value1 <- rnorm(n=100, mean=1, sd=1) %>% as.data.frame()
value2 <- rnorm(n=100, mean=3, sd=1) %>% as.data.frame()
value3 <- rnorm(n=100, mean=1, sd=2) %>% as.data.frame()
value1$name <- "A1"
value2$name <- "A2"
value3$name <- "A3"
value1 <- rbind(value1,value2,value3)
colnames(value1) <- c("value","name")
ggplot(value1, aes(x = value, y = reorder(name, value, mean)))+
geom_posterior() +
xlab("value") + theme_bw()
Plot
Upvotes: 1