r - 如何使用条形图获得可靠的刻度刻度,这些条形图将数字总结为 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")
解决方案
问题似乎是最后一个文件行。每列结尾的字符串"<++>"
弄乱了数字列MONTANT
。这是解决它的一种方法。
- 将列强制
MONTANT
为数字; - 不能为数字的向量元素变为
NA
,并带有警告"NAs introduced by coercion"
; - 用 . 删除那些行
!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))
推荐阅读
- java - Spring Boot 应用程序中的自定义异常抛出
- jspdf - jsPDF-CustomFonts-support 不适用于 Bangla 字体我正在使用 jspdf-autotable
- java - 我如何将模板发送给用户,用户可以在其中编辑 pdf 并且所有文本框和复选框都内联放置
- laravel - Laravel 在集合中添加属性并在 Vue.js 中显示
- powershell - 日志文件格式被搞砸了
- coordinates - 可以以编程方式从 psd 文件中检索 Photoshop 引导线的坐标吗?
- xamarin - 带有 WebView 控件的 Xamarin ItemTemplate
- php - Laravel 测试响应给定的数据无效
- c++ - 在 Visual Studio Community 2019 中生成包含文件的图表
- python - 如何在多台远程机器上运行 python 脚本?不安装脚本?