Repository navigation
add a fixed plot size option to the plots pane - #18895
Conversation
Plots > Fixed Size... (also the new size menu on the Plots pane toolbar) draws plots at a chosen size in inches, centimeters, or pixels instead of the size of the pane. The RStudio graphics device keeps the pane's reported size separately from the fixed size, so resizing the pane no longer redraws the plot; the pane shows it scaled down to fit and centered, the zoom window scales it to the window at a higher pixel ratio, and exports default to the same size. locator() and manipulator clicks are mapped back to the plot's own coordinates. The setting lives in user state (fixed_plot_size), which the session applies at startup and whenever it changes. Addresses #4422
gtritchie
left a comment
There was a problem hiding this comment.
Review findings below, most severe first. One finding is outside the diff, so it's here:
Publish to RPubs ignores the fixed size (PlotsPane.java:81-89, unchanged). The PR says exported plots default to the fixed size, but Publish still sizes the plot from getPlotFrameSize(), zoomed between 400x350 and 800x700. With a fixed 7x5 in size, the published image is drawn at a pane-derived size and aspect ratio, unlike Save as Image, Save as PDF, and Copy to Clipboard.
| public static String formatValue(double value, String units) | ||
| { | ||
| String pattern = UNITS_PIXELS.equals(units) ? "0" : "0.##"; | ||
| return NumberFormat.getFormat(pattern).format(value); |
There was a problem hiding this comment.
The dialog breaks in the French UI. NumberFormat.getFormat follows the compiled locale (the build ships en,fr), so French users get a comma decimal separator. The result goes into an <input type=number> and is read back with Double.parseDouble.
For example, enter 7 x 5 in and switch to cm: convertValue sets "17,78", the number input rejects it and becomes empty, and OK fails with Invalid Plot Size. A stored fractional size (such as 10.16 cm) also opens blank. Formatting with a locale-independent pattern (e.g. plain Double to string after rounding) avoids this.
There was a problem hiding this comment.
Fixed in c7af0ab. The number inputs are written with formatInputValue, which always uses '.'. NumberFormat is now only used for display text (the toolbar label and the range in the error message), where the locale's separator is right.
| } | ||
|
|
||
| // The label for the Plots pane's size menu, e.g. "7 x 5 in". | ||
| public static String label(FixedPlotSize size) |
There was a problem hiding this comment.
The label and radio state can disagree with the device. They come from the raw user state, but SessionPlots.cpp clamps to 96-2880 px and falls back to Fit to Pane when readObject fails.
For example, .rs.writeUserState("fixed_plot_size", list(enabled = TRUE, width = 100, height = 0.5, units = "in")) shows "100 x 0.5 in" while dev.size() is 30 x 1. A malformed member (e.g. units = 1) disables the fixed size but leaves Fixed Size checked. Reopening the dialog then fails validation on the stored values.
There was a problem hiding this comment.
Fixed in b51b90d. FixedPlotSizeUtils.effectiveSize reads the saved size the way syncFixedPlotSize does: a wrongly typed member or a missing dimension means Fit to Pane, unknown units are inches, and each dimension is clamped to 96-2880 px. The label, the checked menu item, and the dialog's starting values all come from it. Your first example now shows "30 x 1 in", and units = 1 shows Fit to Pane, checked. Both are covered in 608ef73.
| // Maps a point in the Plots pane to the plot's own coordinates: a plot with | ||
| // a fixed size is scaled down to fit the pane and centered in it (see | ||
| // ImageFrame.replaceLocation). | ||
| private Point toPlotPoint(int x, int y) |
There was a problem hiding this comment.
Clicks outside the image map outside the plot. Clicks in the blank area around a centered or scaled plot map to coordinates outside the device (negative, or beyond width/height). They go to locator() and manipulator clicks as-is.
For example, with a 4x3 in plot in a large pane, locator(1) followed by a click left of the image returns a point outside the plot region. This can't happen in Fit to Pane mode, where the image fills the frame. Ignoring or clamping these clicks would keep the old behavior.
There was a problem hiding this comment.
| double fit = std::min( | ||
| static_cast<double>(width) / fixedWidth, | ||
| static_cast<double>(height) / fixedHeight); | ||
| double ratio = graphics::device::devicePixelRatio() * std::max(1.0, fit); |
There was a problem hiding this comment.
The zoom window renders more pixels than it shows. std::max(1.0, fit) means that when the fixed plot is larger than the zoom window, the PNG is still rendered at the full fixed size x DPR and then shrunk by CSS. That happens again on every debounced resize.
For example, a 30x30 in (2880x2880) plot at DPR 2 in a ~1000x800 window renders 5760x5760 (~33 MP) per zoom and per resize, while only ~1600x1600 device pixels are displayed. devicePixelRatio() * fit without the floor renders only what's shown.
There was a problem hiding this comment.
Fixed in 601f20d. The ratio is now devicePixelRatio() * fit, so the PNG has as many pixels as the window shows, whether the plot is shrunk or enlarged. The new zoom e2e test checks this for a 15 x 20 in plot in a 480 x 640 window (it fails with the old max(1.0, fit)), and then for an enlarged 1.5 x 2 in plot.
| await expect(plotsPane.saveAsImageDialog).toBeHidden(); | ||
| }); | ||
|
|
||
| test('locator() maps clicks on a scaled plot to the plot', async ({ rstudioPage: page }) => { |
There was a problem hiding this comment.
The scale-down path isn't tested. A 4x3 in (384x288) plot fits in the default pane, so this only covers the centering offset. The scale < 1 branch of Plots.toPlotPoint never runs, so a bug in the scale math would still pass.
A plot larger than the pane (e.g. 20x15 in) would cover it. The fixed-size branches of handleZoomRequest / handleZoomPngRequest (the ratio parameter) also have no test.
There was a problem hiding this comment.
Added in 608ef73. There's a 15 x 20 in plot scaled down in the pane, with locator() clicked a quarter of the way in from the left and bottom and checked against ndc (0.25, 0.25). A desktop zoom test covers the ratio path for plots both larger and smaller than the window.
| static_cast<double>(width) / fixedWidth, | ||
| static_cast<double>(height) / fixedHeight); | ||
| double ratio = graphics::device::devicePixelRatio() * std::max(1.0, fit); | ||
| ratio = std::min(ratio, static_cast<double>(MAX_FIG_SIZE) / std::max(fixedWidth, fixedHeight)); |
There was a problem hiding this comment.
This clamp is repeated in handleZoomPngRequest, which is the one that matters because it also covers hand-built URLs. Keeping only that one means the limit lives in one place.
There was a problem hiding this comment.
Done in 601f20d; only handleZoomPngRequest clamps now.
| style.position = 'absolute'; | ||
| style.inset = '0'; | ||
| style.margin = 'auto'; | ||
| style.width = 'min(' + w + 'px, 100vw, calc(100vh * ' + w + ' / ' + h + '))'; |
There was a problem hiding this comment.
The same centered aspect-fit CSS (position: absolute; inset: 0; margin: auto; min(100vw, calc(100vh * w / h))) is also in the handleZoomRequest template in SessionPlots.cpp. Plots.toPlotPoint depends on this geometry, and a change to one copy (the outline, an inset fallback) won't reach the other.
There was a problem hiding this comment.
I'd rather keep these separate, since they differ on purpose. The pane never enlarges a plot (the min(<w>px, ...) term) and outlines it, while the zoom window enlarges it to fill the window. They're also built in different places (JSNI in the pane's iframe, and the server-side zoom page), so sharing one string would mean passing CSS between C++ and GWT. toPlotPoint only mirrors the pane's copy, because the zoom window has no click mapping. The scaled-down locator() test in 608ef73 now catches drift between that math and the pane's CSS.
| { | ||
| String url = server_.getGraphicsUrl(plotsState.getFilename()); | ||
| view_.showPlot(url); | ||
| Size size = new Size(plotsState.getWidth(), plotsState.getHeight()); |
There was a problem hiding this comment.
This builds the same Size as plotSize_ a few lines below. Setting plotSize_ / plotSizeFixed_ first and passing plotSizeFixed_ ? plotSize_ : null removes the duplicate and keeps the displayed size and the click-mapping size from drifting apart.
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
Save Plot as Image replaces "Use device pixel ratio" with a Resolution choice (the screen's, or 96/150/300/600 DPI) for plots, and shows the image's size in inches and pixels. The width and height stay in pixels at 96 DPI, so a higher resolution adds detail without changing the layout, and a fixed plot size exports at its size in inches. R's quartz() bitmap devices -- the default on macOS -- don't record the resolution in the files they write (R PR#19076), so Word and other applications inserted those images at the wrong size; this also affected Copy to Clipboard on macOS. After saving a bitmap, RStudio now rewrites it through ImageIO with the resolution when it's missing (a no-op for the other devices), and marks JPEG JFIF densities as dots per inch. Addresses #4422
… fix boolean state getters Review fixes for #4422: - .rs.api.savePlotAsImage() now raises an R error when the save fails (e.g. the image would exceed the bitmap size limit) instead of returning silently with no file. - Save as Image no longer clamps a fixed size larger than the preview area to the screen (which also switched Keep Ratio off); the preview is hidden instead, and the export keeps the fixed size. - generate-prefs.R emits boolean object getters that return a stored false instead of '|| <default>', which turned it into a true default; regenerated the accessors (fixes useDevicePixelRatio and the other true-default booleans, such as the panes' consoleRightOnTop). - locator() clicks beside a centered fixed-size plot no longer show the click feedback, since they aren't reported to R. - The zoom window computes the render pixel ratio from its own devicePixelRatio, so a window on a different display than the main window is rendered sharp rather than at the main window's ratio. - RPubs keeps a fixed plot's size but draws it at a lower pixel ratio when it's larger than the standard 1024 x 768 size, so the page doesn't embed huge images. - The Quartz resolution probe only runs when the bitmap device is Quartz; cairo output already records its resolution. - The e2e afterEach finishes a pending locator() before resetting the console, so a failed locator test can't hang the suite.
gtritchie
left a comment
There was a problem hiding this comment.
Thanks for the fixes. The eight round-1 findings you addressed are resolved, and I'm fine keeping the two aspect-fit CSS copies separate for the reasons you gave.
This round covers the new commits. There are four comments, most severe first.
| // too large to preview (the preview is hidden then, see | ||
| // setPreviewPanelSize), rather than clamped to the screen with its | ||
| // aspect ratio lost | ||
| initialWidth = Math.max(initialWidth, MIN_SIZE); |
There was a problem hiding this comment.
Copy to Clipboard can't copy a fixed plot larger than the window. Dropping the screen clamp on the starting size is right for Save as Image, but it also applies to the Copy to Clipboard dialogs. Their starting size is the plot size (ExportPlotOptions.adaptToSize(..., getPlotSize())), so a large fixed size now hides the preview (setPreviewPanelSize). Those dialogs copy from that preview:
- Web:
CopyPlotToClipboardWebDialogasks the user to right-click the preview image. - Linux desktop:
CopyPlotToClipboardDesktopDialog.doCopyAsBitmapcopies from the previewimgwithcopyImageAtXYToClipboard. - Windows desktop: the metafile dialog's bitmap option inherits the same
copyAsBitmap.
For example, with a 30 x 20 in fixed size, there's nothing to right-click in the web dialog, and the desktop bitmap copy targets a hidden image. macOS desktop isn't affected, because it copies through the session (copyPlotToCocoaPasteboard).
Keeping the screen clamp when previewer_.getLimitToScreen() is true (the copy dialogs pass true) would keep Save as Image's full fixed size while leaving copy working.
There was a problem hiding this comment.
Good catch, though the mechanism was different: ExportPlotDialog.createMainWidget() still clamped every export dialog's starting size to the screen, so 5934d2b never changed anything for either dialog. Fixed in 9621ad2: the clamp now lives in ExportPlotSizeEditor and applies only when previewer_.getLimitToScreen() is true, so the copy dialogs (and the Viewer export) keep it, and Save as Image keeps the fixed size with the preview hidden. The export e2e test now uses a 15 x 20 in plot and checks that Save as Image starts at 1440 x 1920 while Copy to Clipboard is clamped with its preview visible.
| res = gsl::narrow_cast<int>(res * pixelRatio); | ||
| double scaledWidth = width * pixelRatio; | ||
| double scaledHeight = height * pixelRatio; | ||
| if (scaledWidth * scaledHeight > kMaxBitmapPixels) |
There was a problem hiding this comment.
The "reduce its size or resolution" message doesn't reach the Save as Image dialog. The description is stored as an error property. savePlotAs returns the error through the normal RPC path, and JsonRpcResponse::setError leaves properties out by default (includeErrorProperties = false), so the client only gets getSummary(). That's a generic system error ("... error N (Value too large ...)", wording varies by platform). Only .rs.api.savePlotAsImage() reads the description.
For example, a 30 x 20 in plot at 600 DPI is 18000 x 12000 = 216 MP, over kMaxBitmapPixels. The dialog shows "30 x 20 in, 18000 x 12000 pixels" with no warning, then fails with the generic message. Either check the limit in SavePlotAsImageDialog.updateSizeText(), which already computes the pixel count, or send the description to the client.
There was a problem hiding this comment.
Fixed in 9621ad2, both ways. savePlotAs sends the description as the error's client info (the SessionGit / SessionSpelling idiom) and SavePlotAsHandler shows it in place of the summary, so the dialog reports "The image would be 9000 x 12000 pixels; reduce its size or resolution". updateSizeText() also warns next to the size when the pixel count is over 100 MP. The e2e test checks the warning at 600 DPI and the error text on an actual save.
| if (identical(proptype, "boolean")) { | ||
| java <- paste0(java, | ||
| " public final native boolean get", propname, "() /*-{\n", | ||
| " return this && typeof this.", prop, " === \"boolean\" ? this.", prop, " : ", default, ";\n", |
There was a problem hiding this comment.
This fix needs its own NEWS entry. The fix is correct, but it changes behavior outside #4422 for a bug that shipped. v2026.01.0 has return this && this.console_right_on_top || true;, and PaneLayoutPreferencesPane saves consoleRightOnTop = false when the Console is placed bottom-right. Until now that false read back as true, so Console on Right (PaneManager.onLayoutConsoleOnRight, getConsoleRightOnTop() ? 2 : 3) put the Console top-right. With this change it goes bottom-right, as intended. The "Use device pixel ratio" option not persisting is another visible effect.
The repo's CLAUDE.md says "When fixing a bug or adding a new feature, add an entry to the appropriate section ... of NEWS.md", and the exceptions don't apply to a released bug. NEWS has no entry for it. Consider splitting it into its own PR with an issue, or at least adding a Fixed entry.
| test('exporting defaults to the fixed size', async ({ rstudioPage: page }) => { | ||
| await createPlot(page); | ||
| await openFixedSizeDialog(page); | ||
| // The export dialog caps its size at the window's client height minus |
There was a problem hiding this comment.
Minor: since 5934d2b the export dialog no longer caps its starting size, so this comment is out of date. The test would pass at the original 5 x 4 in. Either go back to 4 or reword the comment.
There was a problem hiding this comment.
Reworded in 9621ad2. The comment described the outer clamp above, which was still in effect; the test now uses a size larger than the window instead of staying under the cap.
Review fixes for #4422: - ExportPlotDialog clamped every export dialog's starting size to the screen, so Save as Image never kept a fixed size larger than the window, despite 5934d2b. The clamp now lives in the size editor and applies only to previewers limited to the screen: the copy dialogs (which copy from the preview) keep it, Save as Image keeps the fixed size and hides the preview it can't show. - Save as Image shows when the image would exceed the session's bitmap limit, next to its size, and a refused save reports the session's advice ("reduce its size or resolution") instead of a system error code: the description is sent as the error's client info. - The export e2e test uses a fixed size larger than the window, checks the too-large warning and the save error, and checks that Copy to Clipboard is clamped with its preview visible. It also waits for the file chooser to list its directory before accepting it, since an early accept closes the chooser without saving.
|
This is an optimization that has been long-awaited! Thanks to everyone involved. While using this new feature, I wondered if it might be possible to also incorporate an image compression mechanism. The current output is very close to being ready for use in academic manuscripts, but the file sizes are a bit large. For instance, could a compression method like LZW—commonly used for TIFF files—be implemented? Or perhaps other well-established compression techniques could be added? @kevinushey |
Summary
Plots can now be drawn at a fixed size instead of the size of the Plots pane, so a figure can be iterated on in the IDE the way it will look in the final output, with no
png()/ external viewer loop.locator()and manipulator clicks are mapped from the scaled, centered image back to the plot's coordinates.Exporting at a precise physical size
For a plot pasted into a Word document (or similar) to come out at a precise size, the image file has to carry its resolution: that's how those applications decide an inserted bitmap's physical size.
quartz()bitmap devices, the default on macOS, don't record the resolution in the files they write. This is R PR#19076, which has a patch acknowledged by R-core but not yet committed. PNGs have nopHYs, JPEGs a 72:72 aspect ratio, TIFFs no resolution tags, and BMPs 0 ppm, so Word inserted them at the wrong size. That affected Copy to Clipboard too, since AppKit sizes the copied image from the same file. After saving a bitmap, RStudio now reads its resolution back and, if it's missing or wrong, rewrites the file through ImageIO with the DPI (as the upstream patch does). It also marks the JFIF density as dots per inch, since ImageIO always writes the aspect-ratio form. This is a no-op for Cairo and ragg output, and for Quartz once R records the resolution itself.generate-prefs.Remitted boolean object getters asthis.x || <default>, so a storedfalseread back astruewhenever the default wastrue(unchecking the old "Use device pixel ratio" checkbox never persisted). The generator now checks for a stored boolean, and the regenerated accessors fix the other true-default getters too (enableSplashScreen,showWhatsNew, the GPU options, and the pane layout'sconsoleRightOnTop).Implementation
RGraphicsDevice.cpp) now keeps the pane size reported by the client separately from an optional fixed size. The effective size prefers the fixed one. Client metrics still save and restore the pane's size, so turning the fixed size off after a session restart doesn't leave a stale pane size behind.fixed_plot_sizeuser state ({enabled, width, height, units}).SessionPlots.cppapplies it at startup and onuserState().onChanged, converting it to 96-DPI pixels and clamping it to the supported range. The plots-changed event carries afixedSizeflag, so the client knows how to display the image.ImageFramecan show the image at a given CSS size, scaled down to fit and centered, using pure CSS (min()of the plot size and the frame's viewport), so no JS resize handling is needed.Testing
test-graphics.R): writing the state pinsdev.size()in inches, centimeters, and pixels, clamps out-of-range sizes, and follows the pane again when the setting is turned off.fixed_plot_size.test.ts, desktop-dev): default state; fixed size setsdev.size()and keeps the aspect ratio, and a pane resize (after the metrics RPC lands) leaves the device alone; unit conversion in the dialog; out-of-range sizes are rejected and cancelling restores the menu's checked state; the export dialog defaults to the fixed size;locator()on a centered plot reports its center (verified to fail with the mapping disabled); Fit to Pane restores pane-sized plots.test-graphics.R): PNGs and JPEGs saved through RStudio's export path (.rs.api.savePlotAsImage) record 96 DPI; the raw Quartz output doesn't.test-graphics.R):.rs.api.savePlotAsImage()raises an R error (and writes no file) for an image that would exceed the bitmap size limit; RPubs images for a 30 x 30 in plot are 768 x 768 and 1536 x 1536.sipsand in their raw PNGpHYs/ JFIF / TIFF / BMP fields;NSImage(and so the macOS clipboard) sizes the fixed PNG at its physical size.plots_pane.test.tspasses, including the zoom and save-image tests.Not covered: Windows, the Desktop native menu's radio state (the handlers re-sync the checked state after a cancelled dialog), and pasting into Word itself (verified via the file metadata Word reads, not in Word).
Fixes #4422.