我有一个用以下代码制作的情节:
plot <- ggplot(lmeans, aes(x=Day, y=value*100, group=variable, colour=variable)) +
geom_point(aes(shape=variable), size=4) +
geom_line(aes(linetype=variable), size=1.5) +
ggtitle(paste("Nausea and Vomitting Frequencies by Day for", group_name)) +
ylab("Frequency (%)") +
ylim(0, 40) +
theme(legend.title=element_blank()) +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))
这导致了如下情节:
然而,我希望将这些日子分开标记,而不是作为连续轴给出。当我尝试通过添加scale_x_discrete()
来实现此目的时,我得到以下结果:
其中&#39;边距&#39;在x轴上以不正确的方式改变。如何避免这些难看的变化?
这是复制的最小例子:
require(ggplot2)
lmeans <- data.frame(Day=c(0,1,2,3,0,1,2,3),
variable=c("x","x","x","x","y","y","y","y"),
value=c(5,4,2,1,7,3,2,0))
plot <- ggplot(lmeans, aes(x=Day, y=value, group=variable, colour=variable)) +
geom_point(aes(shape=variable)) +
geom_line(aes(linetype=variable)) +
ylim(0, 10) +
scale_x_discrete() +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))
print(plot)
产生这个:
答案 0 :(得分:4)
如果没有scale_x_discrete
并将Day
设置为因素,则情节看起来不错:
ggplot(lmeans, aes(x=factor(Day), y=value, group=variable, colour=variable)) +
geom_point(aes(shape=variable), size=4) +
geom_line(aes(linetype=variable), size=1.5) +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))
给出:
使用scale_x_discrete
时,您可以添加expand
参数以设置边距。一个例子:
ggplot(lmeans, aes(x=factor(Day), y=value, group=variable, colour=variable)) +
geom_point(aes(shape=variable), size=4) +
geom_line(aes(linetype=variable), size=1.5) +
ylim(0, 10) +
scale_x_discrete("Day", expand=c(0.05,0.1), breaks=c(0,1,2,3)) +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))
给出:
答案 1 :(得分:1)
我将scale_x_discrete()
更改为scale_x_continuous()
并使用limits
。这对你有用吗?
ggplot(lmeans, aes(x=Day, y=value, group=variable, colour=variable)) +
geom_point(aes(shape=variable)) +
geom_line(aes(linetype=variable)) +
ylim(0, 10) +
scale_x_continuous(limits = c(-0.5, 4)) +
theme(legend.justification = c(1, 1), legend.position = c(1, 1))
答案 2 :(得分:1)
在审美映射中使用factor(Day)
:
plot <- ggplot(lmeans, aes(x=factor(Day), y=value,
group=variable, colour=variable)) +
geom_point(aes(shape=variable)) +
geom_line(aes(linetype=variable)) +
ylim(0, 10) +
labs(x="Day") +
theme(legend.justification=c(1, 1), legend.position=c(1, 1))
print(plot)