小编use*_*203的帖子

"for"循环只添加最终的ggplot图层

简介:当我使用"for"循环将图层添加到小提琴图(在ggplot中)时,添加的唯一图层是由最终循环迭代创建的图层.然而,在模拟循环将生成的代码的显式代码中,添加了所有层.

详细信息:我正在尝试创建具有重叠层的小提琴图,以显示估计分布对于多个调查问题响应重叠或不重叠的程度,按地点分层.我希望能够包含任意数量的地方,因此每个地方我都有一列数据框,并且我尝试使用"for"循环来为每个地方生成一个ggplot图层.但是循环只会从循环的最后一次迭代中添加该层.

此代码说明了问题,以及一些失败的建议方法:

library(ggplot2) 

# Create a dataframe with 500 random normal values for responses to 3 survey questions from two cities
topic <- c("Poverty %","Mean Age","% Smokers")
place <- c("Chicago","Miami")
n <- 500
mean <- c(35,  40,58,  50, 25,20)
var  <- c( 7, 1.5, 3, .25, .5, 1)
df <- data.frame( topic=rep(topic,rep(n,length(topic)))
                 ,c(rnorm(n,mean[1],var[1]),rnorm(n,mean[3],var[3]),rnorm(n,mean[5],var[5]))
                 ,c(rnorm(n,mean[2],var[2]),rnorm(n,mean[4],var[4]),rnorm(n,mean[6],var[6]))
                )
names(df)[2:dim(df)[2]] <- place  # Name those last two columns with the corresponding place name.
head(df) 

# This "for" loop seems to only execute the …
Run Code Online (Sandbox Code Playgroud)

for-loop r ggplot2

11
推荐指数
1
解决办法
3449
查看次数

如何将R ggplot图形存储为html代码段

我通过使用ggplotly()和htmltools函数(例如h3()和)创建各种对象来创建html文档html()。然后,我将它们作为列表提交htmltools::save_html()以创建html文件。

我想将ggplot图表直接添加为图像,而不是附加所有杂乱无章的钟声。最后,我将创建一个自包含的html文件(无依赖项),而内容丰富的工作会使该文件过大。

是否有一些将ggplot对象转换为html类型对象的函数?还是我必须将ggplot保存为.png文件,然后将.png文件读入我添加到save_html()函数列表中的某个对象中?

我的R代码如下所示:

library("tidyverse")
library("plotly")
library("htmltools")

HTMLOut <- "c:/Users/MrMagoo/My.html")
df <- data.frame(x=1:25, y=c(1:25*1:25))

g7 <- ggplot(df,aes(x=x, y=y)) + geom_point()
p7 <- ggplotly(g7)  # I would like to use something other than ggplotly here. Just capturing the ggplot as an image would be fine.

# create other objects to add to the html file
t7 <- h2(id="graph7", "Title for graph #7")
d7 <- p("description of graph 7")

save_html(list(t7, p7, d7), HTMLOut)
# …
Run Code Online (Sandbox Code Playgroud)

r ggplot2 htmltools

4
推荐指数
2
解决办法
1591
查看次数

标签 统计

ggplot2 ×2

r ×2

for-loop ×1

htmltools ×1