ggplot2 scales issue

After I run this code

ggplot(bar, aes(x = Provinces, y = Male, fill = "male")) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_bar(aes(x = Provinces, y = Female), stat = "identity", position = "dodge", fill = "red") +
  ggtitle("Presidential Election Results by Gender and City") +
  scale_fill_manual(values = c("male" = "blue", "female" = "red"))

This is what am receiving
Error: Unknown colour name: female

It seems your data is untidy, as you are having to write two geom_bar statements to do the work of one geom*

I would guess that you need to use pivot_longer() to restructure your data.

library(tidyverse)

data <- data.frame(
  Provinces = c("Provinces 1", "Provinces 1", "Provinces 2", "Provinces 2"),
  gender = c("male", "female", "male", "female"),
  count = c(10, 15, 20, 25)
)

ggplot(data, aes(x = Provinces, 
                 y = count, 
                 fill = gender)) +
  geom_col(position = "dodge")+
  scale_fill_manual(values = c("male"="blue","female"="red"))

Can you share part of your dataframe using dput(head(yourdataframe, 10))?

structure(list(Provinces = c("CENTRAL", "COPPERBELT", "EASTERN",
"LUAPULA", "LUSAKA", "MUCHINGA", "NORTH-WESTERN", "NORTHERN",
"SOUTHERN", "WESTERN"), Male = c(317037, 507825, 403632, 254570,
598927, 185458, 180988, 280756, 359918, 183348), Female = c(349563,
518072, 492707, 312433, 644692, 216200, 205689, 325590, 422149,
263945), Total = c(666600, 1025897, 896339, 567003, 1243619,
401658, 386677, 606346, 782067, 447293)), row.names = c(NA, 10L
), class = "data.frame")

see below my data frame

Provinces Male Female Total
1 CENTRAL 317037 349563 666600
2 COPPERBELT 507825 518072 1025897
3 EASTERN 403632 492707 896339
4 LUAPULA 254570 312433 567003
5 LUSAKA 598927 644692 1243619
6 MUCHINGA 185458 216200 401658
7 NORTH-WESTERN 180988 205689 386677
8 NORTHERN 280756 325590 606346
9 SOUTHERN 359918 422149 782067
10 WESTERN 183348 263945 447293


Try this:

library(tidyverse)

data <- structure(list(Provinces=c("CENTRAL","COPPERBELT","EASTERN",
"LUAPULA","LUSAKA","MUCHINGA","NORTH-WESTERN","NORTHERN",
"SOUTHERN","WESTERN"),Male=c(317037,507825,403632,254570,
598927,185458,180988,280756,359918,183348),Female=c(349563,
518072,492707,312433,644692,216200,205689,325590,422149,
263945),Total=c(666600,1025897,896339,567003,1243619,
401658,386677,606346,782067,447293)),row.names=c(NA,10L
),class="data.frame") %>% as_tibble()

data %>% 
  pivot_longer(cols = c("Male", "Female"), names_to = "Gen", values_to = "Count") %>% 
  ggplot(aes(x = Provinces, y = Count, fill = Gen)) +
  geom_col(position = "dodge") +
  labs(Title = "mytitle",
       x = "Provinces",
       y = "Count",
       fill = "Genre") +
  theme_classic()


Thank you. I can work with this.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.