简体   繁体   中英

struggling with scaling a secondary axis on a plot that is not a percentage

I'm getting crazy here, please help me. I'm new to R and this is why. I have a graph here in which I'm trying to plot steps given against time needed to fall asleep (in minutes) and I decided to plot user ID on the x axis and the other two variables in a vertical axis of its own: The result is as follows:

废话!

I'm not happy with many things. The scaling of the line plot and the scale of the secondary axis, the width of the columns in geom_col, and the y axis labels, I mean, the user IDs have 10 digits each and it shows up as a potency. Can you please help me out with all I mentioned, specially with the scaling of the secondary axis? I've searched and searched and can't do it.

The code is this one:

ggplot(data= sleep_steps) +
+ geom_col(mapping = aes(x=Id, y=AVGSteps), fill = 'cyan') +
+ geom_line(mapping = aes(x=Id,y=AVGMinToFallAsleep)) +
+ labs(title = "Relationship between Steps and Time to Fall Asleep") +
+ scale_y_continuous(sec.axis = sec_axis(~ . - 8*60*60, name = "Minutes to Fall Asleep"))

And the table is like this:

head(sleep_steps)
          Id  AVGSteps  AVGKcal AVGMinToFallAsleep AVGTotalMinAsleep
1 1503960366 12116.742 1816.419           22.92000          360.2800
2 1644430081  7282.967 2811.300           52.00000          294.0000
3 1844505072  2580.065 1573.484          309.00000          652.0000
4 1927972279   916.129 2172.806           20.80000          417.0000
5 2026352035  5566.871 1540.645           31.46429          506.1786
6 2347167796  9519.667 2043.444           44.53333          446.8000

I'm clueless. Since it is not a percentage nor is a datetime variable, I'm not sure what to do. I've tried to change the trans argument in sec_axis function but no success. The structure of the data frame is all num.

Thank you!

You need Id as a factor to start because they are individuals, not actual numbers. Insert before plot

sleep_steps$Id <- as.factor(sleep_steps$Id)

Without the code for your data to check, I would also say that you need another fill colour for your second scale, but you are using geom_line which is not normally how you would plot individuals because they are not connected. You may need to reconsider that. Normally you would plot all your data with boxplots which would show the averages and the quartiles etc.

If you are looking for an actual RELATIONSHIP, then you need to look into an lm plot LINK HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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