如果我将分组数据帧传递给函数,然后更改分组变量的名称,原始数据框的分组将更改为新名称.当函数返回时(我没有返回更改的数据帧),原始数据框的名称保持不变,但分组更改为不存在的名称.
# test scoping of group_by() which appears to change groups
library(dplyr)
muck_up_group<-function(mydf){
mydf<-mydf %>% rename(UhOh=Species)
}
dont_muck_up_group<-function(mydf){
mydf<-mydf %>% ungroup()
mydf<-mydf %>% rename(UhOh=Species)
}
data("iris")
iris<-as_tibble(iris) %>% group_by(Species)
iris
# A tibble: 150 x 5
# Groups: Species [3]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <fctr>
# 1 5.1 3.5 1.4 0.2 setosa
muck_up_group(iris) # original grouping changed to column name that doesn't exist
iris
# A tibble: 150 x 5
# Groups: UhOh …Run Code Online (Sandbox Code Playgroud) 这来自ggplot2文档:
# Better example
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
library(reshape2) # for melt
crimesm <- melt(crimes, id = 1)
if (require(maps)) {
states_map <- map_data("state")
ggplot(crimes, aes(map_id = state)) + geom_map(aes(fill = Murder), map = states_map) + expand_limits(x = states_map$long, y = states_map$lat)
last_plot() + coord_map()
ggplot(crimesm, aes(map_id = state)) + geom_map(aes(fill = value), map = states_map) + expand_limits(x = states_map$long, y = states_map$lat) + facet_wrap( ~ variable)
}
Run Code Online (Sandbox Code Playgroud)
我不明白这是如何工作的,因为states_map数据框中没有公共标识符,它使用"region"来命名states列和crimes标记状态的数据框"states".是什么将数据与地图联系起来?
在这个例子中,海报重命名地图数据框的列以符合数据,但ggplot2文档似乎没有这样做.怎么样?当我重命名states_map上面示例中的列时,"状态"对于两个数据帧都是通用的,它会破坏代码. …
我一直在玩双变量 choropleth 地图,并且一直在研究如何创建类似于Joshua Stevens在这里显示的那个的 2d 图例:
为了说明这一挑战,我们不需要使用地图。下面的代码就足够了:
#test desired legend appearance
library(ggplot2)
library(reshape2)
#use color scheme shown here http://www.joshuastevens.net/cartography/make-a-bivariate-choropleth-map/
bvColors=c("#be64ac","#8c62aa","#3b4994","#dfb0d6","#a5add3","#5698b9","#e8e8e8","#ace4e4","#5ac8c8")
legendGoal=melt(matrix(1:9,nrow=3))
test<-ggplot(legendGoal, aes(Var1,Var2))+ geom_tile(aes(fill = as.factor(value)))
test<- test + scale_fill_manual(name="Var1 vs Var2",values=bvColors,drop=FALSE)
test
Run Code Online (Sandbox Code Playgroud)
它创建了一个看起来像我想要的图例的图,但当然图例是所有级别的垂直条。我希望图例看起来像情节本身。有没有办法做到这一点?谢谢!
与这个较旧的问题相比,使用字符串表达式进行过滤现在确实适用于 Arrow 数据集,但它们在反应式 Shiny 环境中不起作用。 有解决方法吗?这是箭头化的 Shiny 演示应用程序。我添加了一个 textInput() 小部件并尝试过滤其中的内容。在下面的代码中,分配给的subset是操作所在的位置。Arrow 版本在 Shiny 上下文之外工作,并且在 Shiny 内部使用字符串文字而不是表达式工作。
library(shiny)
library(arrow)
library(dplyr)
library(stringr)
faithful <- faithful |>
mutate(size = if_else(eruptions > 4,"Big One","Little One"))
faithful_arrow <- faithful |>
as_arrow_table()
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
textInput("size","Size",value = "Big"),
sliderInput("bins",
"Number of bins:",
min = 1, …Run Code Online (Sandbox Code Playgroud)