【发布时间】:2015-02-22 11:36:51
【问题描述】:
我真的很喜欢 ggplot2 包,但经常遇到所谓的基本问题,让我停了好几个小时。我有一堆来自以前模拟的 ggplot 对象,我希望更改(形状、alpha、颜色、大小)的外观,而不是重新运行模拟。 stackoverflow 上有很多类似的问题,但它们都略有不同,我还没有能够提取整体知识来轻松创建绘图。如果有人能指出我正确的方向,我很高兴。
这些图是使用与此等效的代码创建的:
ggplot(data=df) + geom_point(aes(x=Test, y=Val, ymax=max(Val), group=State, colour=State), shape=20, position=position_dodge(.5), alpha=1/2)
这是一个可重现的例子:
require(ggplot2)
# Create some data.
state <- c(TRUE,FALSE)
effect <- c(0.5, 1.0)
test <- c("A","B")
# Create combinations.
df <- expand.grid(Test=test, State=state, Effect=effect)
# Add some values.
df$Val <- rnorm(nrow(df))
# The plots were created this way.
gp <- ggplot(data=df) + geom_point(aes(x=Test, y=Val, ymax=max(Val), group=State, colour=State), shape=20, position=position_dodge(.5), alpha=1/2)
gp <- gp + facet_wrap(~ Effect)
gp <- gp + theme_bw()
print(gp)
# Change colours and re-order legend works.
cols <- c("TRUE" = "red","FALSE" = "blue")
gp <- gp + scale_colour_manual(values = cols, breaks = c("TRUE", "FALSE")) # Change and re-order legend.
print(gp)
# Change 'shape', 'size' or 'alpha' this way does not work.
cols <- c("TRUE" = 1,"FALSE" = 3)
gp <- gp + scale_shape_manual(values=cols, breaks = c("TRUE", "FALSE"))
print(gp)
cols <- c("TRUE" = 5,"FALSE" = 10)
gp <- gp + scale_size_manual(values=cols, breaks = c("TRUE", "FALSE"))
print(gp)
cols <- c("TRUE" = 1,"FALSE" = 1/5)
gp <- gp + scale_alpha_manual(values=cols, breaks = c("TRUE", "FALSE"))
print(gp)
也许我应该以不同的方式创建情节?任何 cmets 表示赞赏。我发现如果我在“aes”中指定“形状”,我可以改变形状,但并非没有问题:
# Put shape inside aes.
gp <- ggplot(data=df) + geom_point(aes(x=Test, y=Val, ymax=max(Val), group=State, colour=State, shape=State), position=position_dodge(.4), alpha=1/2)
gp <- gp + facet_wrap(~ Effect)
gp <- gp + theme_bw()
print(gp)
# Change colours and re-order legend this way works (but adds another legend).
cols <- c("TRUE" = "red","FALSE" = "blue")
#gp <- gp + scale_colour_manual(values = cols) # Changes colour.
gp <- gp + scale_colour_manual(values = cols, breaks = c("TRUE", "FALSE")) # Changes colour, but adds a second legend when re-ordered.
print(gp)
# Try to change shape.
cols <- c("TRUE" = 1,"FALSE" = 3)
gp <- gp + scale_shape_manual(values=cols, breaks = c("TRUE", "FALSE")) # Back to one legend, but 'FALSE' does not have a symbol.
print(gp)
# Change 'size' etc. this way does not work.
cols <- c("TRUE" = 5,"FALSE" = 10)
gp <- gp + scale_size_manual(values=cols, breaks = c("TRUE", "FALSE"))
print(gp)
【问题讨论】:
-
df$Val
-
对不起,'comb' 应该是 'df' 来生成数字。现在改变了。