首页 > 解决方案 > 如何使用条形图获得可靠的刻度刻度,这些条形图将数字总结为 ggplot (R) 中的单个条形?

问题描述

我有一个简单的 ggplot 条形图,它显示有关学费的信息。它从具有以下列的数据框中检索其信息:

您可以在本文末尾仔细查看此数据(csv 格式)。

我图中的每个条形代表一个不同的购买地点。对于每次购买,这些条都会堆叠多种颜色(与其数量成正比)。这是我的情节:

示例图

如您所见,缩放明显关闭(y 轴上的 10.28 刻度大约是 215.25 刻度的三分之一)。

我应该如何使缩放准确以及导致这个不准确的 y 轴的原因是什么?

这是我的原始 csv 文件:

"DATE"      ;"MONTANT";"LIEU"                      ;"CAUSE"
"2020-01-25";    67.17;"Coop Cégep"                ;"Notes de cours"
"2020-02-24";     7.67;"Coop Cégep"                ;"Notes de cours"
"2020-01-30";    10.28;"Coop Cégep"                ;"Cahiers d'exercices"
"2020-03-02";   215.25;"Omnivox (Cégep Lanaudière)";"Frais de scholarité"
"2020-01-22";   114.60;"Coop Cégep"                ;"Romans, Notes de cours"
"2020-08-27";    78.33;"Coop Cégep"                ;"Romans, Notes de cours"
"<++>"      ;     <++>;"<++>"                      ;"<++>"

这是我用来生成此图像的代码:

#!/bin/Rscript

# LIBRARIES ----

library(ggplot2)
library(RColorBrewer)

# CSV's ----

expenses <- head(data.frame(read.csv("paiements.csv", header=TRUE, sep=";")), -1)
expenses$DATE  <- as.Date(expenses$DATE)

# PLOTS ----

# Bar plot with different expenses sorted by location
expenses_df <- ggplot(expenses, aes(LIEU, MONTANT, fill=MONTANT)) +
    geom_bar(stat="identity") +
    geom_jitter(width=0.1, height=0, shape=18, size=4) +
    labs(
             title="Montants de diverses dépenses scholaires",
             x="Lieu",
             y="Montant") +
    theme(plot.title = element_text(hjust=0.5))

# JPEG ----

jpeg(
        file="paiements.jpg",
)

print(expenses_df)

dev.off()

数据dput格式

expenses <-
structure(list(DATE = c("2020-01-25", "2020-02-24", "2020-01-30", 
"2020-03-02", "2020-01-22", "2020-08-27"), MONTANT = c(67.17, 
7.67, 10.28, 215.25, 114.6, 78.33), LIEU = c("Coop Cégep", "Coop Cégep", 
"Coop Cégep", "Omnivox (Cégep Lanaudière)", "Coop Cégep", 
"Coop Cégep"), CAUSE = c("Notes de cours", "Notes de cours", 
"Cahiers d'exercices", "Frais de scholarité", "Romans, Notes de cours", 
"Romans, Notes de cours")), row.names = c(NA, -6L), class = "data.frame")

标签: rggplot2plotbar-chartgeom-bar

解决方案


问题似乎是最后一个文件行。每列结尾的字符串"<++>"弄乱了数字列MONTANT。这是解决它的一种方法。

  1. 将列强制MONTANT为数字;
  2. 不能为数字的向量元素变为NA,并带有警告"NAs introduced by coercion"
  3. 用 . 删除那些行!is.na(.)

代码如下。

expenses$MONTANT <- as.numeric(expenses$MONTANT)
expenses <- expenses[!is.na(expenses$MONTANT), ]

现在强制日期列进行分类"Date"和绘图。CAUSE我已经用定义它们的颜色填充了这些条。

expenses$DATE  <- as.Date(expenses$DATE)

library(ggplot2)

ggplot(expenses, aes(LIEU, MONTANT, fill = CAUSE)) +
  geom_bar(stat="identity") +
  geom_jitter(width=0.1, height=0, shape=18, size=4) +
  labs(
    title="Montants de diverses dépenses scholaires",
    x="Lieu",
    y="Montant") +
  theme(plot.title = element_text(hjust=0.5))

在此处输入图像描述


推荐阅读