我正在尝试生成一个交互式图形,在左侧显示美国地图,在右侧显示直方图。直方图中的条形图上的每个数据点都对应一个状态,并在选择后反映X数据量。美国地图和直方图都在生成,但是当我单击美国地图上的某个州时,整个直方图会变成红色,而不仅仅是对应于所选州的条形图。
谢谢。
Image of generated graph and issue
当前使用的代码:
library(ggplot2)
library(maps)
usaMap <- map_data("state")
USArrests <- read.csv("Test.csv")
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)