Гистограмма в R - я могу сделать это в Python и в Таблице, но возникли проблемы в R - PullRequest
0 голосов
/ 25 января 2020

Попытка построить простую гистограмму в R.

Это ссылка на данные (https://data.world/makeovermonday/2020w3-is-it-time-to-treat-sugar-like-smoking). Мне нужно построить простую гистограмму, которая показывает потребление сахара только для детей (есть 3 строки с детьми), только для этого столбца c (2014 / 15-2015 / 16). Я знаю, что это как-то связано с select() и filter(), но у меня проблемы - благодарю за любую помощь!

Вложение того, что я сделал в Python и Таблице. Пытаюсь повторить в R: Изображение

Ответы [ 6 ]

1 голос
/ 26 января 2020

Без использования пакета dplyr и только ggplot2, вы можете использовать subset, чтобы выбрать часть вашего фрейма данных, и scale_x_discrete, чтобы упорядочить свою ось X. Вы также можете использовать geom_col вместо geom_bar(stat = "identity"):

library(ggplot2)
colnames(df)[1] = "Age Bracket"
ggplot(data = subset(df, grepl("Children",`Age Bracket`)), 
       aes(x = `Age Bracket`, y = `(2014/15-2015/16)`))+
  geom_col(fill = "#b2dbf4",width = 0.8 )+
  geom_hline(yintercept = 5, colour = "gray", lty = 2) +
  scale_x_discrete(limits = c("Children 1.5-3 years","Children 4-10 years","Children 11-18 years"))+
  labs(y = "Free sugars as % of total energy", 
       title = "Children's sugar intake as a % of total energy\n(2014/15-2015/16)") 

enter image description here

1 голос
/ 26 января 2020

Вы можете сделать следующее:

library(ggplot2)
library(dplyr)
library(httr)
library(readxl)

GET("https://query.data.world/s/wxcskq64mo3kn4zga2fjpm2aaucmxk", write_disk(tf <- tempfile(fileext = ".xlsx")))
df <- read_excel(tf)
names(df) <- c("age_bracket", "years_08_09", "years_10_11", "years_12_13", "years_14_15")

df$age_bracket <- factor(df$age_bracket, levels = df$age_bracket, ordered = TRUE)

ggplot(
  data = df %>% filter(grepl("Children", age_bracket)),
    aes(
      x = age_bracket,
      y = years_08_09
    )
  ) +
  geom_bar(stat = "identity", fill = "#CFE5F3") +
  geom_hline(yintercept = 5, colour = "gray", lty = 2) +
  labs(
    x = "Age Bracket", 
    y = "Free sugars as % of total energy", 
    title = "Children's sugar intake as a % of total energy"
  ) +
  theme_bw()
1 голос
/ 26 января 2020

Вот очень уродливый график, но должен дать вам что-нибудь для начала?

library(ggplot2)
library(dplyr)

data <- read.csv("C:/2020W3.csv")

names(data) <- c("AgeGroup", "2008-2009", "2010-2011", "2012-2013", "2014-2015")

data$AgeGroup <- as.factor(data$AgeGroup)
ggplot(
  data = data %>% select(AgeGroup, `2008-2009`),
  aes(
    x = AgeGroup,
    y = `2008-2009`
  )
) +
  geom_bar(stat = "identity") +
  geom_hline(yintercept = 5)

Рад помочь в случае необходимости.

0 голосов
/ 26 января 2020

Ключевой частью ggplot2 является то, что данные должны быть аккуратными , чтобы они работали должным образом. Иногда это может быть немного хлопотно, но обычно окупается.

Это мое полное решение: усердно работаю над получением данных в аккуратном формате, а затем ggplot2 намного проще:

library(dplyr)
library(ggplot2)
library(readxl)
library(tidyr)

sugar <- read_excel("data/MakeoverMondayData.xlsx")
children_2014_2016 <- sugar %>% 
  gather("period", "intake", -1) %>% 
  separate(1, c("category", "age"), sep = " ", extra = "merge") %>% 
  filter(
    category == "Children",
    period == "(2014/15-2015/16)"
  ) %>% 
  mutate(age = factor(age, levels = c("1.5-3 years", "4-10 years", "11-18 years"), ordered = TRUE))

label_ <- data.frame(x = 2, y = 5, label = "5% of total energy")

children_2014_2016 %>% 
  ggplot() + 
  geom_bar(stat = "identity", fill = "lightblue", aes(x = age, y = intake)) + 
  geom_hline(yintercept = 5, linetype = "dashed", colour = "grey") +
  geom_text(data = label_, aes(x = x, label = label, y = y)) +
  ggtitle("Children's free sugars intake (as % of of total energy)") +
  labs(x = "Age", y = "Free sugars as % of of total energy") +
  theme_minimal()

enter image description here

Теперь я попытаюсь объяснить, как это работает:

  1. Первым шагом было бы привести данные в порядок. Для этого я собираюсь tidyr::gather столбцов, чтобы иметь два новых столбца, period и intake. -1 означает, что я собираю всего, кроме первого столбца.
gather("period", "intake", -1)
Разделите первый столбец, чтобы на следующем этапе я мог лучше контролировать фильтрацию. Я разделяю первый столбец на два новых столбца: category (Children, Adult, et c.) И age. Аргумент extra = "merge" присутствует потому, что при разделении пробелом будет более двух столбцов, поэтому я хочу объединить дополнительные элементы в последнем столбце.
separate(1, c("category", "age"), sep = " ", extra = "merge")
Фильтр по категории и периоду. Это довольно просто
filter(
  category == "Children",
  period == "(2014/15-2015/16)"
) %>% 
Измените столбец age на упорядоченный фактор, чтобы я мог контролировать порядок появления категорий на графике
mutate(age = factor(age, levels = c("1.5-3 years", "4-10 years", "11-18 years"), ordered = TRUE))

После этого все, кроме метки "5 % от общей энергии "довольно стандартный ggplot2, я думаю.

0 голосов
/ 26 января 2020
#Load the xlsx library to read the excel sheet
library(xlsx)
#load the tidyverse library for ggplot and others (one line of code for many handful libraries)
library(tidyverse)

#Read the excel sheet, and specify sheet #1 
#Reading strings as Factors is opetional; thus commented it out and my code converts to strins
data.chld.sugar <- read.xlsx("2020W3.xlsx", 1)#, stringsAsFactors = F)

#Check the data; dimension and header
dim(data.chld.sugar)
head(data.chld.sugar)


#Let's clean up the column names or names of the data frame. Will make potting easier
colnames(data.chld.sugar) <- c("Age_group", "Y2008_2009", "Y2010_2011", "Y2012_2013", "Y2014_2015")



#keep only the Children groups by perfrming the filter on the Age-group.
data.chld.sugar.1 <- data.chld.sugar %>%
  filter(Age_group %in% c("Children 1.5-3 years", "Children 4-10 years", "Children 11-18 years"))

#Make sure Age_group is a factor and re-level to order the Children's group in the correct order
data.chld.sugar.1$Age_group <- factor(data.chld.sugar.1$Age_group, levels=c("Children 1.5-3 years", "Children 4-10 years", "Children 11-18 years"))


#Using ggplot, will create the Bar plot and will try to make it very close to the Python output
ggplot(data = data.chld.sugar.1, 
         mapping = aes(x = Age_group,
                       y = Y2014_2015))+
  geom_bar(stat="identity",width=.6)+ #reduce th width of the barplot to mimic the Python plot output
  scale_y_continuous(name="% of sugar intake \n", breaks=c(0,2,4,6,8,10,12,14))+#using the same breaks
  xlab("Age bracket")+
  ggtitle("Children's sugar intake as a % of total energy")
0 голосов
/ 26 января 2020

В R select () используется для извлечения столбцов и filter () для извлечения строк. Я переименовал column1 в «сахар». Ниже приведен код, надеюсь, это поможет!

# Libraries used
library(ggplot2)
library(readr)
library(dplyr)
library(tidyverse)

# Loading data
df = read_csv('2020W3.csv')

# Renaming first column to sugar
df = df %>% rename(sugar = free_sugars_intake_of_total_energy_in_all_age_groups_for_all_paired_years_of_the_ndns_rolling_programme)

#Filtering rows
df1 = df %>% filter(str_starts(sugar, 'Child')) 

#plotting barplot
ggplot(df1, aes(df1$sugar, df1$`2014_15_2015_16`)) + geom_bar(stat = "identity") + 
  ggtitle('Children total intake as % of total energey') + labs(x = 'Age Bracket', y = '% of sugar intake') 

Снимок кода

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...