函数的R图是空的

时间:2017-07-21 13:51:05

标签: r ggplot2

在尝试传递“AZ”等状态时,它会打印一个空图。我希望这个函数在这个意义上是动态的,我可以使用它们的缩写来查看各种状态的图,而不是循环来同时打印所有的图。标题也需要是动态的。

谢谢!

Plotbydistrictbystate <- function(st){
       myplot <- ggplot(subset(queryResults, queryResults$state == "st"), 
                 aes(x=districtGUID, y=Proportion, fill=Page)) +
                 geom_bar(position = "fill",stat="identity") + 
                 theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
                 scale_y_continuous(labels = percent_format()) + ggtitle("Plot of st")
print(myplot)
}
Plotbydistrictbystate(AZ)

enter image description here

3 个答案:

答案 0 :(得分:1)

Plotbydistrictbystate <- function(st){
       myplot <- ggplot(queryResults %>% filter(state == st), 
                 aes(x=districtGUID, y=Proportion, fill=Page)) +
                 geom_bar(position = "fill",stat="identity") + 
                 theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
                 scale_y_continuous(labels = percent_format()) + ggtitle(paste("Plot of", st))
       print(myplot)
}
Plotbydistrictbystate("AZ")

答案 1 :(得分:0)

看起来你的函数对输入参数没有任何作用......也许尝试类似:

Plotbydistrictbystate <- function(st){
       myplot <- ggplot(subset(queryResults, queryResults$state == as.character(st)), 
                 aes(x=districtGUID, y=Proportion, fill=Page)) +
                 geom_bar(position = "fill",stat="identity") + 
                 theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
                 scale_y_continuous(labels = percent_format()) + ggtitle(paste("Plot of",st))
print(myplot)
}
Plotbydistrictbystate(AZ)

请注意,转换为字符时可能会出错...

答案 2 :(得分:0)

所以这似乎是一个小修复。但这有效。

Plotbydistrictbystate <- function(st){
    myplot <- ggplot(queryResults[queryResults$state == st,], 
          aes(x=districtGUID, y=Proportion, fill=Page)) +
          geom_bar(position = "fill",stat="identity") + 
          theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
          scale_y_continuous(labels = percent_format()) + ggtitle(paste("Plot of", st))
    print(myplot)
}

Plotbydistrictbystate("WI")