Home > Blockchain >  How do to delete a bar in ggplot?
How do to delete a bar in ggplot?

Time:09-03

I just want a bar chart, it can only be Private or Public, how can I get rid of one of the columns, or how can I separate them into two graphs.

pp <- ggplot(data1, aes(x=WellClass)) 
pp geom_bar(aes(y = ..prop.., group = 1))

enter image description here

CodePudding user response:

Filter the data you're inputting into the function.

Depending on the structure of data1, this might be done by:

  • data1$Public
  • data1[colname=="Public"]

CodePudding user response:

Instead of doing the calculation within ggplot, it is easier to create a table just for plotting. It is easier to specify what you want as you have everything available in columns. Since you didn't provide any data, I made some up.

library(ggplot2)
library(dplyr)
    
plot_data <- data1 %>% 
  group_by(WellClass) %>% 
  tally() %>% 
  # ungroup() %>% 
  mutate(prop = n / sum(n))

plot_data 
# A tibble: 2 × 3
  WellClass     n  prop
  <chr>     <int> <dbl>
1 Private      43 0.422
2 Public       59 0.578

Now you can either use facet_wrap, but then you will still see the other column, just empty.

ggplot(plot_data, aes(x= WellClass))  
  geom_col(aes(y = prop))  
  facet_wrap(~ WellClass)

enter image description here

Or you can filter the data before plotting like this:

# plot Private
plot_data %>% 
  filter(WellClass == "Private") %>% 
  ggplot(aes(x= WellClass))  
  geom_col(aes(y = prop)) 

enter image description here

And switch the filter for plotting the Public part. And maybe adjust the column width and other aspects.

data:

data1 <- data.frame(WellClass = c(rep("Private", 43), rep("Public", 59)),
                    other_info = rep(1:2, 51)
                    )
  • Related