ggplot Дискретная легенда Непрерывные данные

Я новичок в программировании на R, но мне нравится писать код! Я создал GIF, соединив вместе несколько участков карты. К сожалению, моя легенда относится к конкретному году создания карты, и в результате GIF показывает легенду, метки которой перемещаются вверх и вниз. Я думаю, что решение состояло бы в том, чтобы легенда ссылалась на весь фрейм данных, а не на данный год. Как мне это сделать?

Ссылка на гифку: https://1drv.ms/i/s!Ap-NxMqZOClHqgsFHSxo-kR1pLrr

##This is the R-Code I used for the year 1950:

kansas1950 <- readShapePoly("KansasCOUNTIES.shp")

## Kansas Winter-Wheat Planted from Quickstats

kansas1950.acres <- read.csv(file = "KWW 19502016 QuickStatsEst.csv",
stringsAsFactors = FALSE)

## Create a smaller dataset by retaining the kansas Acres in 1950 and the FIPS
## FIPS, which will be used for matching and merging with the input shapefile
smaller.data1950 <- data.frame(FIPS = kansas1950.acres$FIPS, Acres = kansas1950.acres$X1950)
smaller.data1950 <- na.omit(smaller.data1950)
## Join the two datasets using their common field
matched.indices1950 <- match(kansas1950@data[, "FIPS"], smaller.data1950[, "FIPS"])
kansas1950@data <- data.frame(kansas1950@data, smaller.data1950[matched.indices1950, ])

## Compute the cartogram transformation of each county using its population
## with the degree of Gaussian blur = 0.5
kansas1950.carto <- quick.carto(kansas1950, kansas1950@data$Acres, blur = 0.5)
## Convert the object into data frame
kansas1950.carto <- gBuffer(kansas1950.carto, byid=TRUE, width=0)
kansas1950.f <- fortify(kansas1950.carto, region = "FIPS")
## Merge the cartogram transformation with the kansas map shapefile
kansas1950.f <- merge(kansas1950.f, kansas1950@data, by.x = "id", by.y = "FIPS")
# Plot of the transformed polygons, where each county is
## further shaded by their acreage (lighter means bigger)

my_map1950 <- ggplot(kansas1950.f, aes(long, lat, group = group, 
fill = kansas1950.f$Acres)) + geom_polygon() +
scale_fill_continuous(breaks = c(0, 10000, 100000, 200000, 526000), 
      labels = c("0 Acres","10k Acres", "100k Acres", "200k Acres", "526k Acres"),
      low = "black",
      high = "purple"
) +
labs(x=NULL, y=NULL) + labs(fill = "Acres Planted") 
# Remove default ggplot layers
my_map1950 <-my_map1950 + theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(), axis.ticks=element_blank(),
      axis.text.x=element_blank(),axis.text.y=element_blank(),
      axis.line = element_line(colour = NA)) 
# Citation
my_map1950 <- my_map1950 + labs(caption = "USDA-NASS Quick Stats") + ggtitle("1950 Kansas Winter-Wheat Acres Planted")
my_map1950
# Save a higher resolution PNG
png('my_map1950kwwpurp.png', units="in", width=10, height=8, res=300)
my_map1950
dev.off()

person gm007    schedule 10.10.2017    source источник
comment
Добро пожаловать в СО. Сначала прочтите это руководство на MCVE, чтобы помочь другим помочь вам. .   -  person mnm    schedule 10.10.2017


Ответы (1)


Предполагая, что это то, что вы хотите, попробуйте добавить это на свой график (но, конечно, указав свои собственные нижние и верхние пределы):

+ scale_fill_gradient(limits = c(0, 10))

У меня есть образец df, который работал:

df <- data.frame(x = 1:10)
p <- ggplot(df, aes(x, 1)) + geom_tile(aes(fill = x), colour = "white")
p + scale_fill_gradient(limits = c(0, 10))
p + scale_fill_gradient(limits = c(0, 20))

Вот график со шкалой от 0 до 10.

Вот график со шкалой от 0 до 20.

EDIT: О, теперь я вижу, что вы вызвали scale_fill_continuous() в своем коде. Попробуйте добавить аргумент limits, аналогичный тому, что я сделал для этого.

person kmoty    schedule 10.10.2017