【问题标题】:Add discrete labels to ggplot2 plot with continuous scale将离散标签添加到具有连续比例的 ggplot2 图
【发布时间】:2016-03-14 17:26:47
【问题描述】:

我正在尝试将离散标签添加到具有连续比例的ggplot2 图。虽然使用stat_function 有很多问题(即关于plotting multiple functions)以及许多关于如何使用不同比例的问题,但我无法理解如何在这个特定实例中更改比例。

剧情如下:

myfun1 <- function(x) (13.076-96.543)*x + (-44.056 +102.057)*x^2 + (17.856 -42.996)*x^3 + (-2.996  + 7.444)*x^4 + (0.190 -0.450)*x^5 + 100.088 + 75.215 # average vs. lowest
myfun2 <- function(x) 13.076*x -44.056*x^2 + 17.856*x^3 -2.996*x^4 + 0.190*x^5 + 100.088 # lowest
myfun3 <- function(x) (13.076-183.093)*x + (-44.056 +229.447)*x^2 + (17.856 -99.353)*x^3 + (-2.996  + 17.517)*x^4 + (0.190 -1.080)*x^5 + 100.088 + 67.115 # highest vs. lowest

df <- data.frame(x = c(0, 6), y = c(0, 6))

myplot_weekday <- ggplot(data = df, aes(x = x, y = y)) + 
  stat_function(fun = myfun3, aes(color = "Highest")) +
  stat_function(fun = myfun2, aes(color = "Lowest")) +
  stat_function(fun = myfun1, aes(color = "Average")) +
  theme_minimal() +
  scale_colour_manual("Students' Course Grade", values = c("red", "black", "blue")) +
  theme(legend.position = "top") +
  theme(text=element_text(size= 14, family= "Times")) +
  ylab("Minutes of Videos Watched") +
  xlab("Weekday")

我尝试添加“星期日”、“星期一”、“星期二”、“星期三”、“星期四”,而不是 x 轴上的连续标签(0、2、4 和 6), “星期五”和“星期六”,但我觉得我以错误的方式接近这个。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以设置任何中断(将获得标签)和您想要的相应标签:

    + scale_x_continuous(breaks = 0:6,
        labels = paste0(c("Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"), "day"))
    

    【讨论】:

    • 这很简单。显示此警告:Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale. 我忽略了它,但是当我保存绘图时,似乎保存了原始(即 0、2、4、6)比例。有关如何保存新的(标记的)比例的任何提示?
    • 可能警告是由于您单独拥有xlab(),最好将name = "Weekday" 添加到scale_x_continuous 并放弃xlab。至于不保存,请确保重新分配绘图对象。如果您只是执行my_plot_weekday + scale_x_cont...,它将在不修改现有绘图对象的情况下显示。您需要my_plot_weekday &lt;- my_plot_weekday +...(或将其添加到原始定义中并重新运行分配)。
    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 2023-03-06
    • 2014-11-14
    • 1970-01-01
    • 2021-03-03
    • 2023-04-09
    • 2014-05-27
    • 2013-12-16
    相关资源
    最近更新 更多