简体   繁体   English

在 R 中使用列作为 x 轴绘制数据?

[英]Plotting data using column as x-axis in R?

I have a dataframe organized as shown below.我有一个 dataframe 组织如下所示。

The 'year' column data is classified as numerical, but the 'country' column data is classified as categorical (will this be problematic?). 'year' 列数据被归类为数值,但 'country' 列数据被归类为分类(这会有问题吗?)。

I would like to be able to line plot a specific country's sales over time.我希望能够随着时间的推移将 plot 列在特定国家/地区的销售量上。

df <- read.table(header=TRUE,text='
    Country   Sales   Year
    USA       956     2018
    USA       855     2017
    UK        635     2018
    UK        588     2017
')

If possible, I would like to create numerous plots in a single go.如果可能的话,我想在单个 go 中创建多个图。 I am able to plot the sales data by year without filtering country using this code, but I used facet_wrap to isolate each plot by year.我可以按年份 plot 销售数据,而无需使用此代码过滤国家/地区,但我使用 facet_wrap 按年份隔离每个 plot。 What I would really like to do is plot "year" on the x-axis and isolate each plot by country.我真正想做的是 X 轴上的 plot “年”,并按国家/地区隔离每个 plot。 Unfortunately, I do not have enough "karma" points to insert an image of the output picture.不幸的是,我没有足够的“业力”点来插入 output 图片的图像。

ggplot(data = df,
         aes(x = Country,
             y = Sales,
             col = Year)) +
  geom_point() +
  facet_wrap(~Year) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

@Vivid @生动

Try to use code bellow:尝试使用下面的代码:

df1  %>%
  ggplot(aes(x=Year, y=Sales)) + 
  geom_line() +
  facet_grid(. ~ Country)

you're best off using a for-loop with the function print to plot your graphs你最好使用带有 function 的 for 循环打印到 plot 你的图表


#get colnames of dataframe (df) to make a list of variable names to loop over.
colNames <- names(df)

#Variable you want on your x axis
X <- df$Year

#then for every variable in your list, print the desired plot
for(i in colNames){
  plt <- ggplot(df, aes_string(x= X, y=i)) +
geom_point() + theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())
  print(plt)
  Sys.sleep(2)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM