library(ggplot2)
rm(list=ls())
bar=read.csv("C:/Users/spider shiyas/Desktop/internship/r/output/bangalore/Area.csv")
attach(bar)
df = data.frame(HSI=HSI,Category)
pic=ggplot(df, aes(x=Category,y=HSI, fill=Category)) +
geom_bar(stat = "identity", aes(width=0.3)) +
geom_text(aes(label=HSI, y=HSI+4*sign(HSI)),size=5)+
scale_y_continuous(breaks = seq(-100,100, 10), labels = 100 + seq(-100, 100, 10))+
coord_flip() +
theme_bw()
pic
ggsave(filename="Area.jpg", plot=pic,path="C:/Users/spider shiyas/Desktop/internship/r/output/bangalore")
我已经为1个变量,即Area做了这个。同样,我还有其他变量Age,Income,Source等。
如何以各自的名义保存所有图表? HSI和Category是每个文件的列。
一次性使用ggplot读取多个文件并保存多个图
答案 0 :(得分:1)
您可以使用for循环遍历文件名并读取数据并使用它创建绘图
删除路径,因为输入csv和jpg都将在同一路径中
显示错误是因为文件名由完整目录
组成我的修改
library(ggplot2)
rm(list=ls())
filenames=list.files(path ="C:/Users/spider shiyas/Desktop/internship/r/output/bangalore/" ,pattern= '*.csv', full.names = TRUE)
for (filename in filenames){
bar=read.csv(filename)
attach(bar)
df = data.frame(HSI=HSI,Category)
pic=ggplot(df, aes(x=Category,y=HSI, fill=Category)) +
geom_bar(stat = "identity", aes(width=0.3)) +
geom_text(aes(label=HSI, y=HSI+4*sign(HSI)),size=5)+
scale_y_continuous(breaks = seq(-100,100, 10), labels = 100 + seq(-100, 100, 10))+
coord_flip() +
theme_bw()
pic
ggsave(filename=gsub(".csv",".jpg",filename), plot=pic)
}
或者您可以使用以下代码保存在其他目的地
我的修改2
library(ggplot2)
rm(list=ls())
filenames=list.files(path ="C:/Users/spider shiyas/Desktop/internship/r/output/bangalore/" ,pattern= '*.csv', full.names = TRUE)
for (filename in filenames){
bar=read.csv(filename)
attach(bar)
df = data.frame(HSI=HSI,Category)
pic=ggplot(df, aes(x=Category,y=HSI, fill=Category)) +
geom_bar(stat = "identity", aes(width=0.3)) +
geom_text(aes(label=HSI, y=HSI+4*sign(HSI)),size=5)+
scale_y_continuous(breaks = seq(-100,100, 10), labels = 100 + seq(-100, 100, 10))+
coord_flip() +
theme_bw()
pic
ggsave(filename=gsub(".csv",".jpg",basename(filename)), plot=pic,path="C:/Users/spider shiyas/Desktop/internship/r/output/bangalore/")
}
在文件名中,我只提供了使用basename函数删除路径的文件名