I have the following simple code for generating a bar chart using the geom_col command in ggplot2:
plt <- ggplot(data)
geom_col(aes(Participations,Country), fill = BLUE, width = 0.6)
My data is a simple dataframe with two variables, Countries
and Participations
, where each country corresponds to a number. The result I get sorts the rows based on the alphabetical order of the countries. How can I modify this to reorder the bar chart based on the number of participations of each country?
I've tried using the reorder()
function, but I'm not sure about the correct syntax.
CodePudding user response:
The correct syntax of reorder
(in the context of ggplot2
) is (aes(x = reorder(x, -y), y = y)
or (aes(x = reorder(x, y), y = y)
, depending if you want to start with the highest or lowest value of y
.
Also make sure fill = "blue"
, unless BLUE
is another specified vector that corresponds to a real color.
library(tidyverse)
set.seed(123)
Country <- c("USA", "UK", "ESP", "FR", "ITA", "BRA", "JAP", "CHN", "ZAF", "DEU")
Participations <- sample(1:10, size = 10, replace = TRUE)
data <- data.frame(Country, Participations)
ggplot(data)
geom_col(aes(x = reorder(Country, -Participations),
y = Participations), fill = "blue", width = 0.6)
xlab("Country")