How do I create columns in a geom_col chart in R?

37 views Asked by At

So I am trying to use the following code to create a column chart that has 2 columns, best frequency and high frequency, imposed onto each other for each species, except I can't get the fill function to only fill in the smaller variable, it instead creates a color chart for the larger one.

Below is the code I am using, the first image is my result, the second is something along the lines of what I want. I am using ggplot, ggthemes and forcats as packages. Any help would greatly be appreciated, thank you!

ggplot(data = penta_calcs, mapping = aes(x = Best_frequency_of_hearing_kHz + High_frequency_of_hearing_limit_kHz, y = fct_reorder(Species, Clade), fill = High_frequency_of_hearing_limit_kHz)) + geom_col() + labs(title = "Best frequency of hearing in non-avian dinosaurs", x = "Hearing frequency (kHz)", y = " ") + scale_color_colorblind()

Result I get

Result I want along the lines of

1

There are 1 answers

0
Josep Pueyo On

As I said in comments, if you provide a sample of your data is easier. However, I can imagine that the solution is probably move from wide to long data. I can adjust the answer once you provide the data.

library(tidyverse)

df <- tibble(
  class = letters[1:5],
  high_frequency = sample(1:10, 5, replace = T),
  best_frequency = sample(1:10, 5, replace = T),
)

# Transform data from wide to long before plotting

df |> 
  pivot_longer(-class) |> 
  ggplot(aes(x = class, y = value, fill = name)) +
  geom_col()

Created on 2024-02-11 with reprex v2.0.2

Does your data look like the one I created?