我有一个.csv
文件,其中有城市。这样的文件看起来像:
city_name
madrid
barcelona
barcelona
madrid
sevilla
sevilla
madrid
sevilla
barcelona
palma
madrid
leon
sevilla
cadiz
sevilla
cadiz
barcelona
leon
cadiz
cadiz
barcelona
madrid
leon
leon
leon
madrid
madrid
sevilla
barcelona
palma
leon
cadiz
palma
我想代表一个barplot
。到目前为止,这是我所拥有的:
但是您可能会注意到,leon
不会出现3次,而是出现6次(该城市是palma
)。该条形图是正确的,但是xlab
(x轴)与它所代表的内容不一致。
我在R-Shiny中的代码:
library(shiny)
ui <- fluidPage(
plotOutput("cities")
)
server <- function(input, output) {
wd.datapath = paste0(getwd(), "/assets")
wd.init = getwd();
setwd(wd.datapath)
d.in = read.csv("cities.csv", header = TRUE)
cities = d.in$city_name
unique_cities = unique(cities)
output$cities <- renderPlot({
barplot(table(c(cities)), names = unique(cities))
})
}
shinyApp(ui = ui, server = server)
我该如何实现?感谢您的帮助。
答案 0 :(得分:2)
只需删除 names 参数,并将barplot
默认为table
输出的names属性。 table
按字母顺序对值进行排序,而unique()
则按数据中显示的顺序返回不同的值列表。
cities = c("madrid", "barcelona", "barcelona", "madrid", "sevilla", "sevilla", "madrid",
"sevilla", "barcelona", "palma", "madrid", "leon", "sevilla", "cadiz", "sevilla",
"cadiz", "barcelona", "leon", "cadiz", "cadiz", "barcelona", "madrid", "leon",
"leon", "leon", "madrid", "madrid", "sevilla", "barcelona", "palma", "leon", "cadiz", "palma")
table(cities)
# cities
# barcelona cadiz leon madrid palma sevilla
# 6 5 6 7 3 6
unique(cities)
# [1] "madrid" "barcelona" "sevilla" "palma" "leon" "cadiz"
barplot(table(cities))
答案 1 :(得分:0)
我认为,如果您按以下方式编辑代码段,则可能对您有用:
output$cities <- renderPlot({
summary <- as.data.frame(table(c(cities)))
barplot(summary$Freq, names = summary$Var1)
})
答案 2 :(得分:0)
用barplot(table(cities))
替换第19行。您正在使用c()
函数,该函数基本上检索整数向量,而R实际上代表的是names
参数。
library(shiny)
ui <- fluidPage(
plotOutput("cities")
)
server <- function(input, output) {
wd.datapath = paste0(getwd(), "/assets")
wd.init = getwd();
setwd(wd.datapath)
d.in = read.csv("cities.csv", header = TRUE)
cities = d.in$city_name
unique_cities = unique(cities)
print(c(cities))
output$cities <- renderPlot({
barplot(table(cities))
})
}
shinyApp(ui = ui, server = server)
结果: