我正在尝试生成一个水平图,在轴上标记有刻度。
df = data.frame(quality = c("low", "medium", "high", "perfect"),
n = c(0.1, 11, 0.32, 87.45))
require(ggplot2)
require(dplyr)
size = 20
df %>%
ggplot() +
geom_bar(aes(x = quality, y = n),
stat = "identity", fill = "gray70",
position = "dodge") +
geom_text(aes(x = quality, y = n,
label = paste0(round(n, 2), "%")),
position = position_dodge(width = 0.9),
hjust = -0.2,
size = 10, color = "gray50") +
coord_flip() +
ggtitle("") +
xlab("gps_quality\n") +
#scale_x_continuous(limits = c(0, 101)) +
theme_classic() +
theme(axis.title = element_text(size = size, color = "gray70"),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.ticks = element_blank(),
axis.line = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(size = size,
color = ifelse(c(0,1,2,3) %in% c(2, 3), "tomato1", "gray40")))
Run Code Online (Sandbox Code Playgroud)
不幸的是,一个条比另一个长得多,ggplot 部分削减了它的价值。
任何的想法?
我已经尝试过,scale_y_continuous(expand = c(0, 0)但它在刻度文本和条形之间增加了很多差距。
你会需要:
ggplot2(v 3.0.0)的最新版本使用clip = "off"允许在绘图面板外绘制绘图元素的新选项。看到这个问题:https : //github.com/tidyverse/ggplot2/issues/2536
### Need development version of ggplot2 for `clip = "off"`
# Ref: https://github.com/tidyverse/ggplot2/pull/2539
# install.packages("ggplot2", dependencies = TRUE)
library(magrittr)
library(ggplot2)
df = data.frame(quality = c("low", "medium", "high", "perfect"),
n = c(0.1, 11, 0.32, 87.45))
size = 20
plt1 <- df %>%
ggplot() +
geom_bar(aes(x = quality, y = n),
stat = "identity", fill = "gray70",
position = "dodge") +
geom_text(aes(x = quality, y = n,
label = paste0(round(n, 2), "%")),
position = position_dodge(width = 0.9),
hjust = -0.2,
size = 10, color = "gray50") +
# This is needed
coord_flip(clip = "off") +
ggtitle("") +
xlab("gps_quality\n") +
# scale_x_continuous(limits = c(0, 101)) +
theme_classic() +
theme(axis.title = element_text(size = size, color = "gray70"),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.ticks = element_blank(),
axis.line = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(size = size,
color = ifelse(c(0,1,2,3) %in% c(2, 3),
"tomato1", "gray40")))
plt1 + theme(plot.margin = margin(2, 4, 2, 2, "cm"))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.0)于 2018 年 5 月 6 日创建。