Area and Line Graph in R with x-Axis as String

Asked

Viewed 871 times

2

I would like to make an area chart and insert another line chart overlaid. I’m not able to do this, because the x chart that I want to put are strings and it gets all wrong. The picture should look like the chart below that I did in excel. As I will have to do several in a loop, I wanted to automate. I tried to use ggplot2 and plotly, but without success. The dataset can be acquired through the link: https://drive.google.com/file/d/0BwVpSqmgvCe-bFRsS0xxZmhQYnc/view?usp=sharing

inserir a descrição da imagem aqui

1 answer

4


I believe the code below solves your problem.

library(ggplot2)

dados <- read.table(file="resposta.csv", header=T, sep=";")

ggplot(dados, aes(x=X, y=custo_med_gerFV_c_financ)) + 
  theme_bw() +
  geom_area(colour="blue", fill="blue") + 
  geom_line(aes(x=X, y=custo_med_rede), colour="darkorange", size=1.5) +
  theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5)) +
  scale_x_continuous(breaks=dados$X, labels=levels(dados$Disco)) + 
  labs(x="Concessionárias", y="Custo")

inserir a descrição da imagem aqui

  • is exactly that, but the line should be on a second axis. It has how to adapt?

  • How so second axis? Besides the scale on the y axis and the colors, I don’t see another difference between the Excel graph and the ggplot2.

  • Not at all. The chart is perfect. But in other datasets I’ll have to put other variables in the second y-axis that don’t have the same scale as the y-axis variable. I know there’s a ggplot function that does this, but I’m not able to get into the code you sent me. The function name is sec_axis.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.