有光泽-单击直方图未正确突出显示条的地图

时间:2019-04-28 20:05:34

标签: r ggplot2 shiny

我正在尝试生成一个交互式图形,在左侧显示美国地图,在右侧显示直方图。直方图中的条形图上的每个数据点都对应一个状态,并在选择后反映X数据量。美国地图和直方图都在生成,但是当我单击美国地图上的某个州时,整个直方图会变成红色,而不仅仅是对应于所选州的条形图。

谢谢。

Image of generated graph and issue

当前使用的代码:

 library(ggplot2)
 library(maps)

导入数据

 usaMap <- map_data("state")

 USArrests <- read.csv("Test.csv")

定义查找要指向哪个状态的函数。该函数从click中获取输入,并提供被单击状态的名称

 which_state <- function(mapData, long, lat) {
 mapData$long_diff <- mapData$long - long
 mapData$lat_diff <- mapData$lat - lat
 mapData <- mapData[abs(mapData$long_diff) < 20 & 
abs(mapData$lat_diff) < 15, ]
 vLong <- mapData$long_diff
 vLat <- mapData$lat_diff
 mapData$angle <- acos(vLong / sqrt(vLong^2 + vLat^2))
rangeAngle <- tapply(mapData$angle, mapData$region, function(x) 
 max(x) - min(x))
return(names(sort(rangeAngle, decreasing = TRUE))[1])
   }

构建应用

   library(shiny)
    plotMap <- ggplot(usaMap, aes(x = long, y = lat, group = 
  group)) 
  + 
 geom_polygon(fill = "white", color = "black")
 plotArrest <- ggplot(USArrests, aes(x=State, y=Date)) +
 geom_bar(stat = "identity")

ui <- shinyUI(fluidPage(
column(
width = 6,
plotOutput("map", click = "clickMap", width = 430, height = 275)
 ),
column(
width = 6,
plotOutput("arrest", width = 430, height = 275)
   )
  ))

   server <- shinyServer(function(input, output) {
  # intital plots
  output$map <- renderPlot({
  plotMap
  # coord_map(), do not use it. More discussion next section.
   })
  output$arrest <- renderPlot({
plotArrest
 })

点击后的图

observeEvent(input$clickMap, {
xClick <- input$clickMap$x
yClick <- input$clickMap$y
state <- which_state(usaMap, xClick, yClick)

 output$map <- renderPlot(
  plotMap + 
    geom_polygon(data = usaMap[usaMap$region == state,], fill = 
 "yellow") +
    annotate("text", x = xClick, y = yClick, label = state, color 
   = "red"))

 output$arrest <- renderPlot({
  plotArrest + geom_bar(stat = "identity",  size = 1, shape = 2, 
color = "red")
})
})
})
shinyApp(ui, server)

0 个答案:

没有答案