英文:
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))
英文:
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 <- 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(
"mean = ", round(mean(mpg$hwy), 1), "\n",
"sigma = ", round(sd(mpg$hwy), 1)
),
hjust = 0
) +
scale_x_continuous(limits = c(0, 1))
p3 + p1 + p2 +
plot_layout(widths = c(1, 3, 1))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论