我正在尝试生成一个带有标记在轴上的刻度的水平图。
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")))
不幸的是,一个酒吧比其他酒吧长得多,ggplot部分削减了它的价值。
有什么想法吗?
我已经尝试了scale_y_continuous(expand = c(0, 0)
,但它在刻度线文字和条形图之间增加了很多空隙。
答案 0 :(得分:3)
您将需要:
最新版本的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"))
由reprex package(v0.2.0)创建于2018-05-06。
答案 1 :(得分:1)