我在Excel中制作了以下图:
但后来我想我会用ggplot让它更漂亮。我到目前为止:
如果您有点好奇,数据会以我的answer here为基础,尽管它并不重要。该图是一个标准的ggplot2构造,带有一些预处理,x轴通过中间的粗线是用p + geom_hline(aes(yintercept=0))
实现的(p
是ggplot对象)。
我觉得Excel图中的轴配置更好。它强调0线(当数据是金钱时很重要)并且因为你不必从底部一直跟随线路而更容易找到截距。这也是人们在纸上或纸板上绘图时绘制轴的方式。
也可以在ggplot中像这样移动轴吗?我不仅想要这条线,而且还要移动刻度线标签。如果有,怎么样?如果不是,是技术还是设计的原因?如果按设计,为什么做出决定?
答案 0 :(得分:9)
试试这个,
shift_axis <- function(p, y=0){
g <- ggplotGrob(p)
dummy <- data.frame(y=y)
ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))),
ymax=y, ymin=y) +
geom_hline(aes(yintercept=y), data = dummy) +
theme(axis.text.x = element_blank(),
axis.ticks.x=element_blank())
}
p <- qplot(1:10, 1:10) + theme_bw()
shift_axis(p, 5)
答案 1 :(得分:4)
我尝试更改主题的axis.text.x,但只能更改hjust
所以我认为你可以删除axis.text.x,然后用geom_text()添加。
例如:
test <- data.frame(x=seq(1,5), y=seq(-1,3))
ggplot(data=test, aes(x,y)) +
geom_line() +
theme(axis.text.x=element_blank(), axis.ticks.x=element_blank()) +
geom_text(data=data.frame(x=seq(1,5), y=rep(0,5)), label=seq(1,5), vjust=1.5)
也许这些代码很有用。
答案 2 :(得分:0)
只是为了完成baptiste的优秀答案,相当于移动y轴:
package test2;
public class StringLargeException {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
答案 3 :(得分:-3)
正如alistaire评论的那样,可以使用geom_hline
和geom_text
完成,如下所示。
df <- data.frame(YearMonth = c(200606,200606,200608,200701,200703,200605),
person1 = c('Alice','Bob','Alice','Alice','Bob','Alice'),
person2 = c('Bob','Alice','Bob','Bob','Alice','Bob'),
Event = c('event1','event2','event3','event3','event2','event4')
)
df$YM <- as.Date(paste0("01",df$YearMonth), format="%d%Y%m")
rangeYM <- range(df$YM)
ggplot()+geom_blank(aes(x= rangeYM, y = c(-1,1))) + labs(x = "", y = "") +
theme(axis.ticks = element_blank()) +
geom_hline(yintercept = 0, col = 'maroon') +
scale_x_date(date_labels = '%b-%y', date_breaks = "month", minor_breaks = NULL) +
scale_y_continuous(minor_breaks = NULL) +
geom_text(aes(x = df$YM, y = 0, label = paste(format(df$YM, "%b-%y")), vjust = 1.5), colour = "#5B7FA3", size = 3.5, fontface = "bold")