Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim a picture with rmarkdown/html?

I want to include a picture form the web in my markdown document, but I just want the left part of the picture. I searched on how to trim picture with rmarkdown but I found nothing...

Here is an example

---
title: "How to trim?"
output: html_document
---

```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = TRUE, fig.align = 'center')
```

Include picture

```{r pic}
include_graphics("http://ggplot2.tidyverse.org/README-example-1.png")
```

which gave me this HTML output.

enter image description here

If I want to trim the legend (the ~20% right part), how can I do?

I accept any type of answer: relative or absolute specifiation, rmarkdown or html solution, ...

Thanks!

like image 817
abichat Avatar asked Jan 11 '18 09:01

abichat


People also ask

How do I mark an image in R markdown?

To add an image in markdown you must stop text editing, and you do this with the command [Alt text] precedeed by a ! Then you have to add the path to the image in brackets. The path to the image is the path from your directory to the image.

How do I center an image in RMarkdown?

Centering Images You can use the knitr include_graphics() function along with the fig. align='center' chunk option. This technique has the benefit of working for both HTML and LaTeX output. You can add CSS styles that center the image (note that this technique works only for HTML output).

How do I convert RMarkdown to HTML?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.


2 Answers

You can use:

library(magick)
crop <- function(im, left = 0, top = 0, right = 0, bottom = 0) {
  d <- dim(im[[1]]); w <- d[2]; h <- d[3]
  image_crop(im, glue::glue("{w-left-right}x{h-top-bottom}+{left}+{top}"))
}
"http://ggplot2.tidyverse.org/README-example-1.png" %>%
  image_read() %>%
  crop(right = 210)
like image 98
F. Privé Avatar answered Sep 21 '22 17:09

F. Privé


Thanks to @hrbrmstr comment, I found a solution.

library(magick)
library(magrittr)
image_read("http://ggplot2.tidyverse.org/README-example-1.png") %>% 
  image_flop() %>% 
  image_crop("1344x960+250") %>% 
  image_flop()

I'm not sure it's the most efficient with the two image_flop() functions and I don't understand precisly the "1344x960+250" but it works :)

like image 24
abichat Avatar answered Sep 20 '22 17:09

abichat