简体   繁体   English

更改 r 中的 x 轴标签

[英]Changing x-axis labels in r

ive got ggplot (geombar), with names of the months on x-axis.i have some data from different days.我有 ggplot (geombar),在 x 轴上有月份的名称。我有一些来自不同日期的数据。 But i would like to have the names on the axis corresponding to the specific dates.但我希望轴上的名称与特定日期相对应。

Date.          Percent.    Category
2020-02-03.    30.         Apple
2020-02-03.    25.         Banana
2020-02-03.    15.         Citron
2020-02-03.    30.         Orange
2020-02-07.    40.         Apple
2020-02-07.    20.         Orange
2020-02-07.    40.         Banana
2020-04-12.    65.         Apple
2020-04-12.    35.         Banana

Ive got 80 dates from one year我有一年的 80 个日期

ggplot(data, aes(fill=Category, y=percents, x=date)) +
    geom_bar(position="fill", stat="identity")

I assumed this would be a duplicate but I was not able to find this question on stackoverflow, so here is a potential solution:我认为这将是重复的,但我无法在 stackoverflow 上找到这个问题,所以这是一个可能的解决方案:

library(tidyverse)

df <- read.table(text = "Date          Percent    Category
2020-02-03    30         Apple
2020-02-03    25         Banana
2020-02-03    15         Citron
2020-02-03    30         Orange
2020-02-07    40         Apple
2020-02-07    20         Orange
2020-02-07    40         Banana
2020-04-12    65         Apple
2020-04-12    35         Banana", header = TRUE)

df$Date <- as.Date(df$Date)

ggplot(df, aes(fill=Category, y=Percent, x=Date)) +
  geom_bar(position="fill", stat="identity") +
  scale_x_date(labels = unique(df$Date),
               breaks = unique(df$Date)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

Created on 2022-04-01 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2022-04-01


Edit编辑

This excellent answer by @teunbrand provides another approach to your problem: https://stackoverflow.com/a/68746906/12957340 @teunbrand 的出色回答为您的问题提供了另一种方法: https://stackoverflow.com/a/68746906/12957340

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

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