R Statistics Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

In this example, we will use a dataset in a wide format (multiple columns for each record), and we will do the appropriate data manipulation in order to transform it into a long format. Finally, we will use the ggplot2 package to make a stacked plot with that transformed data. In particular, we have data for certain companies. The adjusted sales are sales where the taxes have been removed and the unadjusted sales are the raw sales. Naturally, the unadjusted sales will always be greater than the adjusted ones, as shown in the following table:

  1. Import the ggplot2 and reshape libraries as follows:
library(ggplot2)
library(reshape)
  1. Then load the dataset:
datag = read.csv("./ctgs.csv")
  1. Transform the data into a long format:
transformed_data = melt(datag,id.vars = "Company")
  1. Use the ggplot function to create the plot:
ggplot(transformed_data, aes(x = Company, y = value, fill = variable)) + geom_bar(stat = "identity")

This results in the following output: