how to add a box containing text (mean=….,sigma=…) in the left side and a horizontally laied histogramm in the right side of a plot in r?

huangapple go评论59阅读模式
英文:

how to add a box containing text (mean=....,sigma=...) in the left side and a horizontally laied histogramm in the right side of a plot in r?

问题

我的代码非常简单。我想要绘制mpg数据集中一些列相互对比的图表。但我想在图表的左侧添加一个包含文本(平均=....,标准差=...)的框,并在右侧水平排列一个直方图。当然,直方图和文本框的数据将用作y轴。以下是没有直方图和文本框的简单图表:

    library(ggplot2)
    
    ggplot2::ggplot(data = mpg) + aes_string(x="displ", y="hwy") + geom_point()
英文:

My code is very straighforaward.i want to plot some columns againt each other from mpg dataset.But i wan to to add a box containing text (mean=....,sigma=...) in the left side and a horizontally laied histogramm in the right side of a plot .Of course the histogramm and the text are of the data used as y-axis.Here the simple of the plot witout hist and text box:

library(ggplot2)

ggplot2:: ggplot(data = mpg)+aes_string(x="displ",y= "hwy") +geom_point()

答案1

得分: 1

以下是您提供的代码的中文翻译:

这里并不完全清楚您的最终图表应该是什么样子的。但其中一种选择是创建三个独立的图表,然后使用例如 patchwork 将它们组合在一起:

library(ggplot2)
library(patchwork)

p1 <- ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()

p2 <- ggplot(data = mpg, aes(y = hwy)) +
  geom_histogram(binwidth = 2) +
  labs(y = NULL) +
  coord_cartesian(ylim = range(mpg$hwy))

p3 <- ggplot(mpg) +
  theme_void() +
  annotate(
    geom = "label",
    x = 0, y = .5,
    label = paste0(
      "均值 = ", round(mean(mpg$hwy), 1), "\n",
      "标准差 = ", round(sd(mpg$hwy), 1)
    ),
    hjust = 0
  ) +
  scale_x_continuous(limits = c(0, 1))

p3 + p1 + p2 +
  plot_layout(widths = c(1, 3, 1))

how to add a box containing text (mean=….,sigma=…) in the left side and a horizontally laied histogramm in the right side of a plot in r?

英文:

It's not 100% clear how your final plot should look like. But one option would be to create three separate plots and glue them together using e.g. patchwork:

library(ggplot2)
library(patchwork)

p1 &lt;- ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()

p2 &lt;- ggplot(data = mpg, aes(y = hwy)) +
  geom_histogram(binwidth = 2) +
  labs(y = NULL) +
  coord_cartesian(ylim = range(mpg$hwy))

p3 &lt;- ggplot(mpg) +
  theme_void() +
  annotate(
    geom = &quot;label&quot;,
    x = 0, y = .5,
    label = paste0(
      &quot;mean = &quot;, round(mean(mpg$hwy), 1), &quot;\n&quot;,
      &quot;sigma = &quot;, round(sd(mpg$hwy), 1)
    ),
    hjust = 0
  ) +
  scale_x_continuous(limits = c(0, 1))

p3 + p1 + p2 +
  plot_layout(widths = c(1, 3, 1))

how to add a box containing text (mean=….,sigma=…) in the left side and a horizontally laied histogramm in the right side of a plot in r?

huangapple
  • 本文由 发表于 2023年5月13日 16:49:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定