如何让R语言Plotly保存完整尺寸而非拉伸的图表?
解决Plotly保存HTML图表拉伸问题
问题描述
我用R语言开发,按教程绘制了如下散点图(修正了原代码中yaxis的gridwith笔误为gridwidth):
library(dplyr) library(plotly) data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv") data_2007 <- data[which(data$year == 2007),] data_2007 <- data_2007[order(data_2007$continent, data_2007$country),] slope <- 2.666051223553066e-05 data_2007$size <- sqrt(data_2007$pop * slope) colors <- c('#4AC6B7', '#1972A4', '#965F8A', '#FF7070', '#C61951') fig <- plot_ly(data_2007, x = ~gdpPercap, y = ~lifeExp, color = ~continent, size = ~size, colors = colors, type = 'scatter', mode = 'markers', sizes = c(min(data_2007$size), max(data_2007$size)), marker = list(symbol = 'circle', sizemode = 'diameter', line = list(width = 2, color = '#FFFFFF')), text = ~paste('Country:', country, '<br>Life Expectancy:', lifeExp, '<br>GDP:', gdpPercap, '<br>Pop.:', pop)) fig <- fig %>% layout(title = 'Life Expectancy v. Per Capita GDP, 2007', xaxis = list(title = 'GDP per capita (2000 dollars)', gridcolor = 'rgb(255, 255, 255)', range = c(2.003297660701705, 5.191505530708712), type = 'log', zerolinewidth = 1, ticklen = 5, gridwidth = 2), yaxis = list(title = 'Life Expectancy (years)', gridcolor = 'rgb(255, 255, 255)', range = c(36.12621671352166, 91.72921793264332), zerolinewidth = 1, ticklen = 5, gridwidth = 2), paper_bgcolor = 'rgb(243, 243, 243)', plot_bgcolor = 'rgb(243, 243, 243)')
使用htmltools::save_html(html = fig, file = "file.html")保存后,图表呈现拉伸状态,如何让保存的图表保持完整尺寸?
解决方法
方法1:在布局中指定固定宽高
直接在layout()函数中添加width和height参数,明确设置图表的渲染尺寸,保存后就会按该尺寸显示:
# 在原布局基础上添加宽高配置 fig <- fig %>% layout( width = 1000, # 自定义宽度(单位:像素) height = 700 # 自定义高度(单位:像素) ) # 保存图表 htmltools::save_html(html = fig, file = "file.html")
方法2:使用Plotly专用的saveWidget函数
Plotly对象属于htmlwidgets范畴,用plotly::saveWidget()保存会更适配,默认保留图表原始尺寸,也可手动指定宽高:
# 默认尺寸保存 plotly::saveWidget(fig, file = "file.html") # 指定宽高保存 plotly::saveWidget(fig, file = "file.html", width = 1000, height = 700)
方法3:给save_html添加容器样式
如果坚持使用htmltools::save_html,可以将图表包裹在一个指定宽高的div容器中,限制其渲染范围:
library(htmltools) # 创建带固定尺寸样式的容器 chart_container <- tags$div( style = "width: 1000px; height: 700px;", fig ) # 保存容器内的图表 save_html(html = chart_container, file = "file.html")
内容的提问来源于stack exchange,提问作者stats_noob
相关产品推荐
相关产品推荐

