【发布时间】:2022-01-11 18:31:56
【问题描述】:
我在报告中使用代码,生成图表。问题是有时我们只得到几个类别 - 然后情节看起来非常好,但有时很多类别然后情节变得不可读。
我希望 ggplot 使这些图更宽,但我不知道怎么做。
有人知道怎么做吗?下面是一个例子。
这是可重现示例的简短版本:
tmp_data <- data.frame('topic_main_keyword_category' = c(paste0(c("Avoid Ticks In Dog", "Bedbugs Ticks & Fleas", "Cat & Dog Fleas Difference"), 1:55)),
'topic_search_volume' = sample(seq(10, 550, 10)),
'category_count' = sample(1:55))
multiplier <- max(tmp_data$topic_search_volume) / max(tmp_data$category_count)
ggplot(tmp_data) + geom_col(mapping = aes(x = topic_main_keyword_category, y = category_count, fill = topic_main_keyword_category)) +
geom_line(group = 1, mapping = aes(x = topic_main_keyword_category, y = topic_search_volume/multiplier),
color = 'darkorange1', size=1) +
ylab('Topics count') +
xlab('Categories') +
ggtitle('Topic categories') +
theme_bw(base_size = text_size_on_plots) +
scale_fill_viridis(discrete = TRUE) +
guides(fill = "none") +
scale_y_continuous(
sec.axis = sec_axis(~.*multiplier, name = "Search volume",
labels=function(x) format(x, big.mark = " ", scientific = FALSE))) +
theme(axis.text.x = element_text(angle = 90, hjust=1))
编辑:我想自动制作这些图 - 这意味着它们可以保存为具有适当宽度的 png,而无需手动调整。 最后我做到了(虽然我不认为这是一个最佳的解决方案..):
width <- 5 # image width
if(length(unique(tmp_data$topic_main_keyword_category))<35) { width <- 5}
if(length(unique(tmp_data$topic_main_keyword_category))>=35 & length(unique(tmp_data$topic_main_keyword_category))<55) { width <- 10}
if(length(unique(tmp_data$topic_main_keyword_category))>=55 & length(unique(tmp_data$topic_main_keyword_category))<100) { width <- 15}
if(length(unique(tmp_data$topic_main_keyword_category))>=100) { width <- 25}
g <- ggplot(tmp_data) +
geom_col(mapping = aes(x = topic_main_keyword_category, y = category_count, fill = topic_main_keyword_category)) +
geom_line(group = 1, mapping = aes(x = topic_main_keyword_category, y = topic_search_volume/multiplier),
color = 'darkorange1', size=1) +
ylab('Topics count') +
xlab('Categories') +
ggtitle('Topic categories') +
theme_bw(base_size = text_size_on_plots) +
scale_fill_viridis(discrete = TRUE) +
guides(fill = "none") +
scale_y_continuous(
sec.axis = sec_axis(~.*multiplier, name = "Search volume",
labels=function(x) format(x, big.mark = " ", scientific = FALSE))) +
theme(axis.text.x = element_text(angle = 90, hjust=1))
ggsave('Topics_categories.png', plot = g, width=width)
【问题讨论】:
-
(1) 您可以调整视图的大小,例如,RStudio 的图形窗格、Rterm 的窗口。如果您正在渲染到文件(例如,
pdf(.)),那么图形记录功能(pdf、png、jpg,...)都应该接受尺寸。 (2) 不太理想,但也许有必要……通过刻面将其分成两个图。刻面(没有scales="free_y")比2+单独的图更好,以保持刻面之间的相同视觉高度。分面将情节的组成部分分开,因此可能不太理想。 (3)plot_ly或带有滚动“x”的闪亮 div? -
底线,
ggplot2不会使绘图更宽,它受活动画布的约束。如果该画布是一个查看窗格,您可以用鼠标控制它来调整它的大小;如果画布是用于记录到文件的编程方式,那么您可以使用显式参数来控制它(这对于基于闪亮的解决方案也有效,尽管在某种意义上 plotly 是它自己的野兽)。