简体   繁体   English

使用 R 创建具有负值和正值的柱 plot

[英]Creating bar plot with negative and positive value , using R

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.我想创建一个带有负值和正值的条形 plot,如下所示(第一张图片),中间有一条线 0。 However, the bar plot that I have created has bars that all appear in an upright position (second image).但是,我创建的条形 plot 的条形全部显示为直立的 position(第二张图片)。

第一张图片

第二张图片

May I know how to make my bar plot (Image 2) to be like the bar plot in Image 1?我可以知道如何使我的酒吧 plot(图 2)像图 1 中的酒吧 plot 一样吗?

My code:我的代码:

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

Many thanks.非常感谢。

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()

在此处输入图像描述

However, your changes variable may be coded wrong.但是,您的changes变量可能编码错误。 Here I have showed the same plot, but coded the data as a factor instead.在这里,我展示了相同的 plot,但将数据编码为一个因子。 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()

在此处输入图像描述

To fix this, either change the class of the data in the data frame (here I have saved it as df2 :要解决此问题,请更改数据框中数据的 class(此处我已将其保存为df2

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

...or plot it as numeric with as.numeric like so with the original df data frame: ...或 plot 将它作为带有as.numeric的数字,就像原始df数据框一样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM