R:使用ggplot2在散点图上绘制另一列数据
我现在有一个散点图,只显示了我的数据集中的一列,我从csv中读取。我想同时绘制ATI和BTIR:使用ggplot2在散点图上绘制另一列数据,r,ggplot2,R,Ggplot2,我现在有一个散点图,只显示了我的数据集中的一列,我从csv中读取。我想同时绘制ATI和BTI PP BTI ATI 1 9710 9660 2 10000 9900 3 10300 10100 4 10600 10400 . . . 99 159000 107000 我的代码如下所示: #server.R #Income Percentile Scatterplot incomedata <- read.csv("/Users/mat
PP BTI ATI
1 9710 9660
2 10000 9900
3 10300 10100
4 10600 10400
.
.
.
99 159000 107000
我的代码如下所示:
#server.R
#Income Percentile Scatterplot
incomedata <- read.csv("/Users/mathewsayer/Documents/Work/Level 7/Shiny Flat Tax/Flat Tax App/data/incomedist.csv")
ranges <- reactiveValues(x = NULL, y = NULL)
output$plot1 <- renderPlot({
ggplot(incomedata, aes(x = BTI, y = PP)) +
geom_point() +
coord_cartesian(xlim = ranges$x, ylim = ranges$y)
})
#Brush and zoom on scatterplot
observeEvent(input$plot1_dblclick, {
brush <- input$plot1_brush
if (!is.null(brush)) {
ranges$x <- c(brush$xmin, brush$xmax)
ranges$y <- c(brush$ymin, brush$ymax)
}
else {
ranges$x <- NULL
ranges$y <- NULL
}
})
#server.R
#收入百分比散点图
incomedata为了同时绘制BTI
和ATI
,您需要定义在哪个轴上绘制哪个轴。换句话说,您应该告诉ggplot
您希望打印两列,这在您的代码中缺失,即ggplot(incomedata,aes(x=BTI,y=PP))
。在这段代码中,您要求BTI绘制在x轴上,PP绘制在y轴上,据我所知,您根本不希望PP被绘制
你能试试下面的代码,看看它是否符合你的期望吗
ggplot(incomedata, aes(x = BTI, y = ATI)) +
geom_point() +
coord_cartesian(xlim = ranges$x, ylim = ranges$y)
我不确定您为什么希望百分位数位于y轴上,但以下代码可以满足您的要求:
library(dplyr)
library(shiny)
library(tidyr)
library(ggplot2)
# simulate some data
df_foo = data_frame(
percentile = seq.int(99),
ATI = sort(rnorm(99)),
BTI = sort(rnorm(99))
)
# UI
ui_foo = shinyUI(
plotOutput("plot_foo")
)
# server
server_foo = shinyServer(function(input, output) {
output$plot_foo = renderPlot({
df_foo %>%
gather(key = var_name, value = value, -percentile) %>%
ggplot(aes(x = value, y = percentile, group = var_name, color = var_name)) +
geom_line() +
theme_bw()
})
})
# run the server
shinyApp(ui = ui_foo, server = server_foo)
您的问题更基本的是关于如何在ggplot2
中绘制多个变量,您需要在适当重塑的数据中基本指定组
美学。感谢您的帮助bert和tchakravarty
我把我的数据改成了长格式,效果很好
所以我所做的是:
- 按照@Bert的建议,用一个新的分类列将我的数据重塑为长格式
- 将我的ggplot()更改为:
output$plot1感谢您的回复。现在回想起来,我似乎需要将x轴作为类似“收入”的东西。PP在y轴上是必不可少的。我当前的代码按原样绘制BTI,我在上面添加了一幅图像,这幅图像将阐明我对ATI的目标。您可以轻松地将数据从长格式改为宽格式,然后将所有ATI和BTI值放在一列中,另一个新列将定义每个值所属的类别
(ATI或BTI)。然后,您可以很容易地在X轴上绘制值
列,在y轴上绘制PP值,然后您应该添加属性color=Category
,以便根据值所属的类别(ATI或BTI)为值着色。请看:我在y轴上设置百分位数的原因是用户知道他们的收入,但不知道他们在哪个百分位数。因此,他们会先在x轴上阅读,找到他们在那里的位置,然后再抬头查看百分位数。当然,我将要讨论的问题将使这个问题变得半冗余。