I have this data:
country name value
<chr> <chr> <dbl>
1 Germany Jd 7.1
2 Germany Jc 8.4
3 Germany Ne 1.3
4 France Jd 8.3
5 France Jc 12
6 France Ne 3.7
and I would like to plot it in two groups of bars (with three columns each). Ordered the same as it is in the dataframe: First Germany, second France and the order of the columns Jd, Jc, Ne.
I did:
p <- ggplot(data, aes(x = country, y = value)) +
geom_bar(aes(fill = name), width=0.7, position = position_dodge(width=0.7), stat='identity')
but I get the plot in a different order: first France, then Germany and the order of the columns Jc, Jd, Ne. (seems to be ordered alphabetically).
How can I order the bars in the way I want?
Probably one of the simplest ways to take control on sorting is to convert as.factor()
your ordering columns and define the levels, you'll override any other default ordering:
library(ggplot2)
data$country <- factor( data$country, levels = c("Germany", "France"))
data$name <- factor( data$name, levels = c("Jd", "Jc", "Ne"))
ggplot(data, aes(x = country, y = value,fill = name)) +
# moved the aes() all together, nothing related to the question
geom_bar(width=0.7, position position_dodge(width=0.7), stat='identity')
With data
:
data <- read.table(text = "
country name value
Germany Jd 7.1
Germany Jc 8.4
Germany Ne 1.3
France Jd 8.3
France Jc 12
France Ne 3.7",header = T)