Я хотел бы иметь возможность создать таблицу с одним из столбцов, которые являются графическими, другими текстами. В идеале я бы создал таблицу Excel, но я уверен, что ни один из пакетов R в Excel не может записывать PDF-файлы в ячейки. Думаю, я могу что-то взломать, используя Knittr или Sweave, хотя я точно не знаю, как именно. Любой совет?Создание таблиц R со встроенной графикой
ответ
Я попытался воспроизвести свой пример:
Так что я посмотрел в R набора данных, и используется бейсбол набор данных, хотя у меня есть нытье сомнения, что для бейсбола игроков, gr может выглядеть действительно глупо ...
В любом случае я подготовил два примера использования функции get_bar_df
и попытался как можно больше прокомментировать мой сценарий, чтобы помочь вам использовать его.
Сценарий представляет собой автономный sweave скрипт, который нужно запустить с помощью knitr или sweave
\documentclass{article}
\usepackage[table,dvipsnames]{xcolor}% http://ctan.org/pkg/xcolor
\usepackage[nomessages]{fp}% http://ctan.org/pkg/
\newlength{\maxlen}
\newcommand{\databarright}[2][gray!25]
{%
\settowidth{\maxlen}{\maxnum}%
\addtolength{\maxlen}{\dimexpr2\tabcolsep-\arrayrulewidth}%
\FPeval\result{round(#2/\maxnum:4)}%
\rlap{\color{#1}\hspace*{\dimexpr-\tabcolsep+0.1\arrayrulewidth}\rule[-.05\ht\strutbox]{\result\maxlen}{.95\ht\strutbox}}%
\makebox[\dimexpr\maxlen-2\tabcolsep+\arrayrulewidth][r]{\phantom{XXX}}%
}
\newcommand{\databarleft}[2][red!25]
{%
\settowidth{\maxlen}{\maxnum}%
\addtolength{\maxlen}{\dimexpr2\tabcolsep-\arrayrulewidth}%
\FPeval\result{round(#2/\maxnum:4)}%
\makebox[\dimexpr\maxlen-2\tabcolsep+\arrayrulewidth][r]{\phantom{XXX}}%
\llap{\color{#1}\rule[-.05\ht\strutbox]{\result\maxlen}{.95\ht\strutbox}\hspace*{\dimexpr-\tabcolsep-4\arrayrulewidth}}%
}
\begin{document}
<<load_libraries, echo = FALSE, eval = TRUE, results ="hide">>=
library(knitr)
library(xtable)
@
<<get_bar_df, echo = FALSE, eval = TRUE, results ="hide">>=
#' @title get_databar creates labels for xtable in a dataframe
#' @description It will create two new columns and fill them with values for xtable, it will use the last column
#' @param data the dataframe
#' @param colorpos one color for positive values that is interpretable by the xcolor dvips
#' one of 68 standard colors known to dvips \link{https://en.wikibooks.org/wiki/LaTeX/Colors}, default "grey"
#' @param colorneg one color for negative values default "red"
#' @param transparent, the percentage of transparency passed to labels default 50 use zero for no transparency
#' @param caption, caption passed to xtable.
#' @param vline, add a vertical line at the end of the table default FALSE
#' @return A dataframe with the last two columns edited for xtable
get_bar_df <- function(data,
colorpos = "grey",
colorneg="red",
transparent=50,
caption="",
vline=FALSE)
{
if (transparent!=0){
colorpos <- paste0(colorpos,"!",transparent)
colorneg <- paste0(colorneg,"!",transparent)
}
the_col <- ncol(bsb)
idxneg <- data[,the_col] < 0
idxpos <- data[,the_col] > 0
data[idxneg,"\\phantom{neg}"] <- paste0("\\databarleft[",colorneg,"]{", -data[idxneg,the_col],"}")
data[idxpos,"\\phantom{pos}"] <- paste0("\\databarright[",colorpos,"]{", data[idxpos,the_col],"}")
maxnum <<- max(abs(data[,the_col])) # value assigned in .GlobalEnv for later use by latex
if (!vline) {
xdata <-xtable(data, align = rep("l",ncol(data)+1), caption = caption)
} else {
xdata <-xtable(data, align = c(rep("l",ncol(data)),"|l"), caption = caption)
}
return(xdata)
}
@
<<test, echo = FALSE, eval = TRUE, results ="hide">>=
library(plyr)
library(dplyr)
bsb <- select(baseball, id, year, g, r) %>% filter(year == 1872) %>% transform(gr = g -
r)
bsb1 <- select(baseball, id, year, g, r) %>% filter(year == 1873) %>% transform(gr = g -
r)
xbsb <- get_bar_df(data = bsb, caption="example with default values")
xbsb1 <- get_bar_df(data = bsb1,
colorpos = "MidnightBlue",
colorneg = "Goldenrod",
transparent = 60,
caption = "Another example with MidnightBlue, Goldenrod, transparent= 60, vline=TRUE",
vline=TRUE)
print.xtable(xbsb, sanitize.text.function = identity, file = "bsb.tex", hline.after = NULL, include.rownames =FALSE)
print(xbsb1, sanitize.text.function = identity, file = "bsb1.tex", hline.after = NULL, include.rownames =FALSE)
@
% this must come after the chunk (maxnum is defined in the chunk)
\newcommand{\maxnum}
{%
\Sexpr{maxnum}
}
\input{bsb.tex}
\input{bsb1.tex}
\end{document}
Часть кода приходит из этого отличный пост: https://tex.stackexchange.com/questions/81994/partially-coloring-cell-background-with-histograms
Это абсолютно феноменально, спасибо !!! – rimorob
- 1. Python: графики равных осей с встроенной графикой?
- 2. создание одного exe со встроенной dll
- 3. создание таблиц из «мини-таблиц» в r
- 4. Создание многоуровневых таблиц в R
- 5. Создание объединенных таблиц в R
- 6. rollapply со встроенной ссылкой
- 7. Словарь со встроенной фабрикой?
- 8. R webscraping ряд таблиц со страницы
- 9. Скорость рисования API по сравнению с встроенной графикой
- 10. Создание встроенной логарифмической модели
- 11. Создание встроенной формы, Bootstrap
- 12. Создание обобщенных таблиц из списков (R)
- 13. R: Создание латексных таблиц без кода среды
- 14. Docusign API - проблема со встроенной подписью
- 15. Создание диаграммы в соответствии с графикой
- 16. R: проблема с 3D-графикой на поверхности
- 17. Проблемы с графикой Tukey в R
- 18. рамки со встроенной поддержкой jquery?
- 19. Подгонки данных со встроенной функцией
- 20. Как взаимодействовать со встроенной деятельностью
- 21. Уникальное ограничение со встроенной схемой
- 22. Затемнения банки со встроенной банкой
- 23. Масштабирование со встроенной базой данных
- 24. Ecto предупреждение со встроенной моделью
- 25. Создание фиктивной переменной со многими условиями (R)
- 26. Сделать черепаху графикой inline
- 27. Создание шахматной фигуры с графикой (java апплет)
- 28. Java EE со встроенной базой данных
- 29. Создание таблиц
- 30. Как запустить jupyter Rkernel ноутбук с встроенной графикой на машине без дисплея?
Что бы сделать этот вопрос был бы лучше, если бы вы дали небольшой, воспроизводимый пример. Дайте нам немного данных, покажите нам, как вы создаете таблицу в Knitr или Sweave без изображения, и дайте нам пример изображения, которое вы хотите вставить. – nograpes
Ну, проблема в том, что я еще не знаю однажды использовал Knitr или Sweave, поэтому я не могу быстро создать такой пример. Тем не менее, это то, что я хочу, чтобы он выглядел как в excel, более или менее. Графики будут более привлекательными (ggplot) http://media.juiceanalytics.com/images/blog/excel_positivenegative.gif – rimorob
Возможный дубликат http://stackoverflow.com/questions/16680063/how-can-i-add- a-table-to-my-ggplot2-output – EDi