Question

I create data frame:

crime <- c("Zakłócanie porządku", "Przemoc", "Przestępstwa narkotykowe", "Przestępstwa przeciw mieniu", "Inne przestępstwa")
percentage <- c(62.2, 61.7, 66.7, 73.8, 64.7)
df.prison2 <- data.frame(crime, percentage)
colnames(df.prison2) <- c("Rodzaj przestępstwa", "Odsetek recydywistów (w %)")

And I get plot:

 plot.prison <- ggplot(data=df.prison2, aes(x=crime, y=percentage)) +
   geom_bar(stat="identity") +
   xlab("") +
   ylab(colnames(df.prison2)[2]) +
   coord_flip() +
   ggtitle("Przestępstwa popełniane przez recydywistów") 

Bars are ordered alfabetically but I want to have bars ordered by percentages. So I order data frame:

 df.prison2 <- transform(df.prison2, crime = reorder(crime, percentage))

Now plot looks good, bars are ordered but name of one axis has been changed. ("Odsetek recydywistów (w %)" --> "Odsetek.recydywistów..w...". I have no idea what the reason is. I will be grateful for any advice.

Was it helpful?

Solution

Just do the reordering in the original plot's aes():

plot.prison <- ggplot(data=df.prison2, aes(x=reorder(crime, percentage), y=percentage)) +
  geom_bar(stat="identity") +
  xlab("") +
  ylab(colnames(df.prison2)[2]) +
  coord_flip() +
  ggtitle("Przestępstwa popełniane przez recydywistów") 

plot

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top