Home > database >  Creating bar plot with negative and positive value , using R
Creating bar plot with negative and positive value , using R

Time:01-02

I would like to create a bar plot with negative and positive values, shown as below (first image), where there is a line 0 at the middle. However, the bar plot that I have created has bars that all appear in an upright position (second image).

first image

second image

May I know how to make my bar plot (Image 2) to be like the bar plot in Image 1?

My code:

ggplot(fuel_trend, aes(fuel_type, changes))   geom_col(position = "identity")

Many thanks.

CodePudding user response:

I've tried recreating your data since you didn't provide any in your question. If your data is coded as numeric, this shouldn't be a problem, as shown below.

#### Load Tidyverse ####
library(tidyverse)

#### Recreate Data ####
fuel_type <- c("DIESEL",
          "DIESEL/ELECTRIC",
          "LPG",
          "PETROL",
          "PETROL/ELECTRIC")

changes <- c(-1097.82,
             92.96,
             59.35,
             -55.15,
             88.04)

df <- data.frame(fuel_type,
                 changes)

#### Plot ####
df %>% 
  ggplot(aes(x=fuel_type,
             y=changes)) 
  geom_col()

enter image description here

However, your changes variable may be coded wrong. Here I have showed the same plot, but coded the data as a factor instead. This can also be the case if your variable is coded as a character.

#### Coded as Factor ####
df %>% 
  ggplot(aes(x=fuel_type,
             y=factor(changes))) 
  geom_col()

enter image description here

To fix this, either change the class of the data in the data frame (here I have saved it as df2:

df2 <- df %>% 
  mutate(changes = as.numeric(changes))

...or plot it as numeric with as.numeric like so with the original df data frame:

df %>% 
  ggplot(aes(x=fuel_type,
             y=as.numeric(changes))) 
  geom_col()
  • Related