gpt4 book ai didi

r - ggplot在geom tile的每个tile中添加文本

转载 作者:行者123 更新时间:2023-12-04 12:34:41 25 4
gpt4 key购买 nike

在下面的数据框df

df <- data.frame(
model=c(rep('corolla',3),rep( 'accord',3), rep('sunny',3)),
variable=c('urban_mileage', 'rural_mileage', 'highway_mileage'),
rescale=rnorm(9),
year=c(rep(1998,3),rep( 1997,3), rep(2003,3)),
kmdone=sample(10:100,9)*1e3
)
> df
model variable rescale year kmdone
1 corolla urban_mileage -1.03675182 1998 56000
2 corolla rural_mileage 1.06079162 1998 83000
3 corolla highway_mileage -0.18808551 1998 19000
4 accord urban_mileage -0.05151496 1997 69000
5 accord rural_mileage 0.05219512 1997 54000
6 accord highway_mileage -2.03139240 1997 21000
7 sunny urban_mileage -0.06225862 2003 40000
8 sunny rural_mileage 1.38191440 2003 96000
9 sunny highway_mileage -1.02367124 2003 55000
>


我正在使用geom_tile创建一个热图,如下所示

ggplot(df, aes(variable, model)) + geom_tile(aes(fill = rescale), colour = "white") +
scale_fill_gradient2(low = "red", mid = "white", high = "green") +
labs(x = "",y = "") +
theme(legend.title = element_blank(),
axis.text.x = element_text(angle=30,hjust=1,vjust=1.0),
axis.text.y = element_text(size = 12))


如末图所示,这将按道路类型给出里程的热图表示。

我需要通过两件事来增强它


year作为每个模型的标签添加到右轴上(次要y轴-尽管不赞成:))
与df中一样,在每个图块中显示 kmdone值-黑色文本居中


enter image description here

最佳答案

进行了两个小的修改...将paste(model,year)用于y美学,并添加一个geom_text如图所示...

ggplot(df, aes(variable, paste(model,year))) + geom_tile(aes(fill = rescale), colour = "white") + 
geom_text(aes(label=kmdone)) +
scale_fill_gradient2(low = "red", mid = "white", high = "green") +
labs(x = "",y = "") +
theme(legend.title = element_blank(),
axis.text.x = element_text(angle=30,hjust=1,vjust=1.0),
axis.text.y = element_text(size = 12))


enter image description here

关于r - ggplot在geom tile的每个tile中添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45146315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com