使用R包plotly中ggplotly函数时遭遇线条粗细与图表宽度问题
Hey there, I’ve run into these exact headaches before when working with ggplotly—it can be surprisingly finicky about preserving ggplot’s original styling. Let’s break down how to fix both the line thickness and plot width problems step by step.
1. Fixing Line Thickness Discrepancies
When you set lwd = 0.5 in geom_line(), ggplotly doesn’t always map that value directly during conversion. It tends to adjust line widths on its own, so we need to explicitly override the line traces in the resulting plotly object.
Here’s how to do it:
- First, keep your original ggplot code as is:
graphe_clustering <- ggplot(data=dtaLngC, aes(x=DAT_RLV, y=vol_cso_norm))+ geom_line(aes(color=contrat), lwd = 0.5)+ facet_wrap(~Cluster, scales = "free")+ theme(legend.position="none") - Convert it to a plotly object, then target all line traces to set their width manually:
library(plotly) p <- ggplotly(graphe_clustering) # Adjust line width for all scatter (line) traces p <- p %>% style( traces = which(sapply(p$x$data, function(x) x$type) == "scatter"), line = list(width = 0.5) )
This works because ggplotly converts geom_line to scatter traces with mode="lines", so we’re directly targeting those traces to match your original lwd value.
2. Adjusting Plot Width for Faceted Charts
Faceted plots in ggplotly often end up too narrow or have wonky spacing. You have two solid options to fix this:
Option 1: Set an Explicit Overall Width
If you know how wide you want the plot to be, pass the width parameter directly to ggplotly():
p <- ggplotly(graphe_clustering, width = 1200) %>% style(traces = which(sapply(p$x$data, function(x) x$type) == "scatter"), line = list(width = 0.5))
Tweak the 1200 value (it’s in pixels) to fit your needs—wider values will give each facet more breathing room.
Option 2: Fine-Tune Facet Spacing and Margins
If you want more control over spacing between facets and plot margins, modify the layout directly:
p <- ggplotly(graphe_clustering) %>% style(traces = which(sapply(p$x$data, function(x) x$type) == "scatter"), line = list(width = 0.5)) %>% layout( margin = list(l = 50, r = 50, b = 50, t = 50), # Adjust edge margins annotations = lapply(p$x$layout$annotations, function(anno) { anno$xanchor <- "center" # Center facet titles properly anno$yanchor <- "top" anno }) )
This ensures facets don’t get squished and titles stay aligned neatly.
Bonus: Fixing Other Potential Styling Glitches
Sometimes ggplotly messes with axis labels or theme elements too. If you notice issues like tiny axis text, you can override those in the layout() function:
p <- p %>% layout( xaxis = list(title = list(font = list(size = 12))), yaxis = list(title = list(font = list(size = 12))) )
Give these steps a shot—they should get your interactive plot looking exactly like your static ggplot, but with all the hover functionality of plotly!
内容的提问来源于stack exchange,提问作者JeanBertin

