[英]Add Color to Positive and Negative Horizontal Bar Chart
I would like to create a graph to represent projected vs collected revenue by person and I'm not sure how to do this. 我想创建一个图表来表示预计收入与个人收入比较,但我不确定该怎么做。 The goal would be to have the negative differences plotted as a red vertical bar and positive as black.
目标是将负差绘制为红色竖线,将正差绘制为黑色。
ggplot(appts2,
aes(Provider, Difference),
main = "Difference in Projected vs Actual Revenue") +
geom_bar(fill = ifelse(appts2$Difference < 0, "red", "black"), stat = 'identity') +
coord_flip()
works but isn't coloring things correctly. 可以,但是无法正确着色。
Provider Revenue Visits Ave Total Add Ons Total Scheduled Total Seen Total Not Seen TotalBatchVisits ProjectedRevenue Difference MissingRecords
Smith 40911 539 75.9 38 438 404 82 486 36887.4 -4023.6 53
Antonio 4827 63 76.62 7 88 60 35 95 7278.9 2451.9 -32
Jackson 13832 171 80.89 32 155 161 20 181 14641.09 809.09 -10
Redding 23030 278 82.84 25 164 144 34 178 14745.52 -8284.48 100
You can accomplish this by setting the "fill" aesthetic to a logical statement, such as Difference < 0
. 您可以通过将“填充”美学设置为逻辑语句(例如
Difference < 0
来完成此操作。 ggplot will then fill the bars depending on whether the bar is less than or greater than zero. ggplot将根据条形小于或大于零来填充条形。
Never use the $
operator inside of aes()
(you reference appts2$Difference
). 切勿在
aes()
内使用$
运算符(您引用appts2$Difference
)。 Instead, use the bare column name, which ggplot will then search for in the provided data set. 而是使用裸列名称,然后ggplot将在提供的数据集中搜索该名称。 ggplot orders the data before plotting it, so providing an outside vector with
$
can cause strange conflicts with its intended order. ggplot在绘制数据之前先对数据进行排序 ,因此为外部向量提供
$
会导致其预期顺序产生奇怪的冲突。
library(ggplot2)
set.seed(1)
df <- data.frame(category = letters[1:10], difference = rnorm(10))
g <- ggplot(data = df, aes(y = difference, x = category, fill = difference < 0)) +
geom_col() +
coord_flip()
print(g)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.