[英]How to assign figure titles from a group_by (dplyr) variable when creating multiple plotly figures in R
長期讀者,第一次來這里。
我正在使用plotly和dplyr的group_by(group_by變量的每個級別一個圖)創建多個圖。
在下面的示例中,我每年創建一個繪圖(group_by變量),我想將年份指定為圖形標題。 但是,我無法弄清楚如何使用數據框(或小標題)中存儲的值來分配標題。
任何建議,不勝感激! 謝謝!
require(dplyr)
require(plotly)
# creating data table
d = tibble(year=rep(2016:2017,2), type=c(1,1,2,2), amount=1:4)
d
# creating 2 figures, grouped by year (one for each year).
# Using the same title for each figure (this code works).
chart = d %>%
group_by(year) %>%
do(plots = plot_ly(., values = ~amount, type = 'pie') %>% layout(title="Great Title") )
# printing first plot
chart$plots[1][[1]]
# I'd like the title of each figure to be the year.
# I get an error when I try to assign the title with the year variable.
chart.title = d %>%
group_by(year) %>%
do(plots = plot_ly(., values = ~amount, type = 'pie') %>% layout(title=year) )
這不應該是復雜的,因為你可以通過訪問本地year變量.$year
,因此特殊的一年通過.$year[1]
例如(因為year
每個組中是一個常數)。
但是 ,由於在內部和外部do
重復使用%>%
管道符號,所以您遇到了問題,這使得不可能.
引用分組數據–而是引用當前圖。 您可以通過取消嵌套擺脫此問題:
chart = d %>%
group_by(year) %>%
do(plots = layout(
plot_ly(., values = ~amount, type = 'pie'),
title = paste('Chart of year', .$year[1]))
)
chart$plots[1][[1]]
在tidyverse中, purrr
是迭代元素的工具,也是函數編程的助手。 將purrr
和嵌套的data.frame與列表列結合在一起是一個功能強大的工作流程。 然后,您可以執行與group_by
相同的do
但是功能更強大。
我讀過某處它可以代替dplyr::do
。
這是您的問題的tidyverse
方法
library(dplyr, warn.conflicts = F)
library(plotly)
# for iteration and fonctionnal programming
library(purrr)
# for nesting dataframe
library(tidyr)
# creating the data
d <- tibble(year=rep(2016:2017,2), type=c(1,1,2,2), amount=1:4)
d
#> # A tibble: 4 x 3
#> year type amount
#> <int> <dbl> <int>
#> 1 2016 1 1
#> 2 2017 1 2
#> 3 2016 2 3
#> 4 2017 2 4
當您想按Year工作時,可以按Year嵌套數據,並有一個每年有一行的小標題和一個名為data的列表列,其中的每個元素都是小標題,即該行上年份的初始數據的子集
nested_data <- d %>%
nest(-year)
nested_data
#> # A tibble: 2 x 2
#> year data
#> <int> <list>
#> 1 2016 <tibble [2 x 2]>
#> 2 2017 <tibble [2 x 2]>
purrr
與fonctions map
家庭允許您通過列表迭代。 結合dplyr
動詞,我們將添加一個包含plotly
的列。 map2
接受2個參數,即列表列數據和列年份,並應用函數。得到一個列表,結果將存儲在另一個名為plots的列表列中
charts <- nested_data %>%
mutate(plots = map2(data, year, ~ plot_ly(.x, values = ~amount, type = 'pie') %>% layout(title = .y)))
您可以繼續使用此小標題。 計算出曲線圖並與您的數據一起存儲。
charts
#> # A tibble: 2 x 3
#> year data plots
#> <int> <list> <list>
#> 1 2016 <tibble [2 x 2]> <S3: plotly>
#> 2 2017 <tibble [2 x 2]> <S3: plotly>
要手動打印圖,您可以訪問它
charts$plots[1]
#> [[1]]
您可以purrr
遍歷列表列並打印所有圖。#這將在RStudio查看器中打印圖。print_plot <-圖表%>%select(plots)%>%walk(print)
總之,你可以在更換tidyverse
生態系統, group_by
和do
的nest
和purrr
功能。
charts <- d %>%
nested(- year) %>%
mutate(plots = map2(data, year, ~ plot_ly(.x, values = ~amount, type = 'pie') %>% layout(title = .y)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.