gpt4 book ai didi

r - 减小树状图(或 y 轴)ggplot 的大小

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

我有一个树状图的代码。如何减小树状图(或 y 轴)的大小?

我正在使用此代码作为示例。在我的数据集中,我有大标签,所以我没有足够的空间来包含它。出于这个原因,我想减少用于 y 轴的空间,减少 0 和 150 之间的距离。另外,当我将图形保存为 tiff 时,大部分图形是树状图,我看不清标签。

df   <- USArrests                 # really bad idea to muck up internal datasets
labs <- paste("sta_",1:50,sep="") # new labels
rownames(df) <- labs # set new row names

library(ggplot2)
library(ggdendro)
hc <- hclust(dist(df), "ave") # heirarchal clustering
dendr <- dendro_data(hc, type="rectangle") # convert for ggplot
clust <- cutree(hc,k=2) # find 2 clusters
clust.df <- data.frame(label=names(clust), cluster=factor(clust))
# dendr[["labels"]] has the labels, merge with clust.df based on label column
dendr[["labels"]] <- merge(dendr[["labels"]],clust.df, by="label")
# plot the dendrogram; note use of color=cluster in geom_text(...)
ggplot() +
geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data=label(dendr),
aes(x, y, label=label, hjust=0, color=cluster),
size=3) +
coord_flip() +
scale_y_reverse(expand=c(0.2, 0)) +
theme(axis.line.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
axis.title.y=element_blank(),
panel.background=element_rect(fill="white"),
panel.grid=element_blank())

two muppets

如何减小与此热图相似的树状图的大小?

two muppets
(来源: r-graph-gallery.com)

非常感谢

最佳答案

为了灵活性,我建议将树状图标签放在 x 轴本身上,而不是图中的文本标签。否则无论您为 expand 选择什么值在 y 轴上,某些图像尺寸/尺寸的部分标签可能会被剪掉。

为树状图标签定义调色板:

library(dplyr)
label.colour = label(dendr)$cluster %>%
factor(levels = levels(.),
labels = scales::hue_pal()(n_distinct(.))) %>%
as.character()

为了说明的目的,让一些标签很长:
label.values <- forcats::fct_recode(
label(dendr)$label,
sta_45_abcdefghijklmnop = "sta_45",
sta_31_merrychristmas = "sta_31",
sta_6_9876543210 = "sta_6")

阴谋:
p <- ggplot(segment(dendr)) + 
geom_segment(aes(x=x, y=y, xend=xend, yend=yend)) +
coord_flip() +
scale_x_continuous(breaks = label(dendr)$x,

# I'm using label.values here because I made
# some long labels for illustration. you can
# simply use `labels = label(dendr)$label`
labels = label.values,

position = "top") +
scale_y_reverse(expand = c(0, 0)) +
theme_minimal() +
theme(axis.title = element_blank(),
axis.text.y = element_text(size = rel(0.9),
color = label.colour),
panel.grid = element_blank())
p

# or if you want a color legend for the clusters
p + geom_point(data = label(dendr),
aes(x = x, y = y, color = cluster), alpha = 0) +
scale_color_discrete(name = "Cluster",
guide = guide_legend(override.aes = list(alpha = 1))) +
theme(legend.position = "bottom")

plot

关于r - 减小树状图(或 y 轴)ggplot 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992112/

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