【问题标题】:Visualizing crosstab tables with a plot in R - changing colours用 R 中的绘图可视化交叉表 - 改变颜色
【发布时间】:2018-04-01 09:35:10
【问题描述】:

我在 R 中有以下代码,它是从 here 修改而来的,它绘制了一个交叉表:

#load ggplot2
library(ggplot2)                           

# Set up the vectors                           
xaxis <- c("A", "B")
yaxis <- c("A","B")

# Create the data frame
df <- expand.grid(xaxis, yaxis)
df$value <- c(120,5,30,200)    

#Plot the Data
g <- <- ggplot(df, aes(Var1, Var2)) + geom_point(aes(size = value), colour = "lightblue") + theme_bw() + xlab("") + ylab("") 
g + scale_size_continuous(range=c(10,30)) + geom_text(aes(label = value))

它会生成正确的图形,这很棒,但我希望自定义四个点的颜色,理想情况下,左上角和右下角都是一种颜色,右上角和左下角是另一种颜色。

我试过用:

+ scale_color_manual(values=c("blue","red","blue","red"))

但这似乎不起作用。有什么想法吗?

【问题讨论】:

    标签: r ggplot2 colors crosstab bubble-chart


    【解决方案1】:

    我建议您在数据框中按向量着色,因为您没有提供此功能的列,您可以创建一个,或根据现有列制定规则(我在下面做了):

    g <- ggplot(df, aes(Var1, Var2)) + geom_point(aes(size = value, colour = (Var2!=Var1))) + theme_bw() + xlab("") + ylab("") 
    g + scale_size_continuous(range=c(10,30)) + geom_text(aes(label = value))
    

    重要的部分是:color = (Var2!=Var1),注意我把它放在 geom_point 的审美 (aes) 中

    编辑:如果你想删除图例(你在图表上标注了总数,所以我猜你并不需要它),你可以添加:g + theme(legend.position="none") 来删除它

    【讨论】:

    • 这给出了两个独立的图例
    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2021-07-11
    • 1970-01-01
    • 2017-08-01
    相关资源
    最近更新 更多