0

I have the following code. I want to color the USA value in red. But it keeps coloring the place where the USA would've been if I hadn't reordered it. Why? I've tried changing countries into factors, to no avail.

# Sort the data frame by 'val' in ascending order
df <- df[order(df$val), ]

# plot 
p <- ggplot(data = df, 
            aes(x = reorder(country, val), 
                                      y = val, 
                                      fill = country)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = 
                      ifelse(density_df$country == "USA", "red", "darkblue")) +
  theme_minimal() 

enter image description here

Rnewbie
  • 51
  • 4
  • 3
    Setting your colors using an `ifelse` in `scale_fill_manual` is error prone and I would not recommend to do so. Instead map your condition on the fill aes e.g. do `fill = country == "USA"` and use `scale_fill_manual(values = c("TRUE" = "red", "FALSE" = "darkblue"))`. For more help please provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Jul 30 '23 at 08:35

1 Answers1

0

@stefan is right - you will likely get unexpected results by deviating from the usual syntax in ggplot.

What I think you want to do is this.

In this example, they created a dummy variable that aligns with your version of "USA", ie., the highlighted level. Then they used a call to fill = to create the color difference, which are mapped to the dummy variable. In other words, you would use fill = on the dummy variable (not country) and specify the colors in scale_fill_manual that correspond to the colors you want.

You can put this dummy variable and even the colors directly into your data frame if you'd like.

It is a bit non-intuitive the first few times you see it, but it may help you to think of ggplot arguments as their own set of data elements. Many of those come from your data frame but some tricks require you to set up their own variables.

David
  • 572
  • 3
  • 12