R packages used in this sectionlibrary(DT)
library(gapminder)
library(gghighlight)
library(ggrepel)
library(stargazer)
library(tidyverse)| Variables | Graph | Feature |
|---|---|---|
| Discrete | Bar chart | Lines between bars |
| Continuous | Histogram | No Lines between bars |
x-axis: Election year (1996-2026)y-axis: The average number of candidates in each
electoral districtElection year looks a number, but it is not treated as
a number in bar chartElection year is a number, but the value itself does
not mean anythingx-axis: Vote share (%) in lower house election in Japan
(1996-2026)y-axis: The number of candidatesx-axisy-axisThe lower house election data in Japan:
1996-2026 (hr96-26.csv)
・click hr96-26.csv
and download to your computer
・Read the election data and name it as hr
hr96_21.csv is a collection of Japanese lower house
election data covering 11 national elections (1996, 2000, 2003, 2005,
2009, 2012, 2014, 2017, 2021, 2024, 2026)hr contains [1] "year" "pref" "ku" "kun"
[5] "rank" "wl" "nocand" "seito"
[9] "j_name" "name" "previous" "gender"
[13] "age" "exp" "status" "vote"
[17] "voteshare" "eligible" "turnout" "seshu_dummy"
[21] "jiban_seshu" "nojiban_seshu"
hr has the following 23 variables| variable | detail |
|---|---|
| year | Election year (1996-2017) |
| pref | Prefecture |
| ku | Electoral district name |
| kun | Number of electoral district |
| rank | Ascending order of votes |
| wl | 0 = loser / 1 = single-member district (smd) winner / 2 = zombie winner |
| nocand | Number of candidates in each district |
| seito | Candidate’s affiliated party (in Japanese) |
| j_name | Candidate’s name (Japanese) |
| name | Candidate’s name (English) |
| previous | Previous wins |
| gender | Candidate’s gender:“male”, “female” |
| age | Candidate’s age |
| exp | Election expenditure (yen) spent by each candidate |
| status | 0 = challenger / 1 = incumbent / 2 = former incumbent |
| vote | votes each candidate garnered |
| voteshare | Vote share (%) |
| eligible | Eligible voters in each district |
| turnout | Turnout in each district (%) |
| castvote | Total votes cast in each district |
| seshu_dummy | 0 = Not-hereditary candidates, 1 = hereditary candidate |
| jiban_seshu | Relationship between candidate and his predecessor |
| nojiban_seshu | Relationship between candidate and his predecessor |
hrspc_tbl_ [11,892 × 22] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
$ year : num [1:11892] 1996 1996 1996 1996 1996 ...
$ pref : chr [1:11892] "愛知" "愛知" "愛知" "愛知" ...
$ ku : chr [1:11892] "aichi" "aichi" "aichi" "aichi" ...
$ kun : num [1:11892] 1 1 1 1 1 1 1 2 2 2 ...
$ rank : num [1:11892] 7 6 5 4 3 2 1 8 7 6 ...
$ wl : num [1:11892] 0 0 0 0 0 0 1 0 0 0 ...
$ nocand : num [1:11892] 7 7 7 7 7 7 7 8 8 8 ...
$ seito : chr [1:11892] "無所" "国民党" "文化フォーラム" "共産" ...
$ j_name : chr [1:11892] "浅野光雪" "山田浩" "伊東マサコ" "岩中美保子" ...
$ name : chr [1:11892] "ASANO, KOSETSU" "YAMADA, HIROSHI" "ITO, MASAKO" "IWANAKA, MIHOKO" ...
$ previous : num [1:11892] 0 0 0 0 1 3 1 0 0 0 ...
$ gender : chr [1:11892] "male" "male" "female" "female" ...
$ age : num [1:11892] 45 51 51 43 53 72 47 43 47 61 ...
$ exp : num [1:11892] NA NA NA 2177203 9231284 ...
$ status : num [1:11892] 0 0 0 0 1 2 1 0 0 0 ...
$ vote : num [1:11892] 312 566 616 22209 33503 ...
$ voteshare : num [1:11892] 0.2 0.3 0.4 13.3 20.1 25.7 40 0.2 0.2 0.4 ...
$ eligible : num [1:11892] 346774 346774 346774 346774 346774 ...
$ turnout : num [1:11892] 49.2 49.2 49.2 49.2 49.2 49.2 49.2 51.8 51.8 51.8 ...
$ seshu_dummy : num [1:11892] 0 0 0 0 0 0 0 0 0 0 ...
$ jiban_seshu : chr [1:11892] NA NA NA NA ...
$ nojiban_seshu: chr [1:11892] NA NA NA NA ...
- attr(*, "spec")=
.. cols(
.. year = col_double(),
.. pref = col_character(),
.. ku = col_character(),
.. kun = col_double(),
.. rank = col_double(),
.. wl = col_double(),
.. nocand = col_double(),
.. seito = col_character(),
.. j_name = col_character(),
.. name = col_character(),
.. previous = col_double(),
.. gender = col_character(),
.. age = col_double(),
.. exp = col_double(),
.. status = col_double(),
.. vote = col_double(),
.. voteshare = col_double(),
.. eligible = col_double(),
.. turnout = col_double(),
.. seshu_dummy = col_double(),
.. jiban_seshu = col_character(),
.. nojiban_seshu = col_character()
.. )
- attr(*, "problems")=<pointer: 0x990d31640>
chr means character and
num means numerichr{r, results = "asis"} as chunk option| Statistic | N | Mean | St. Dev. | Min | Max |
| year | 11,892 | 2,011.09 | 9.63 | 1,996 | 2,026 |
| kun | 11,892 | 5.90 | 5.33 | 1 | 30 |
| rank | 11,892 | 2.48 | 1.28 | 1 | 9 |
| wl | 11,892 | 0.48 | 0.67 | 0 | 2 |
| nocand | 11,892 | 3.96 | 1.12 | 2 | 9 |
| previous | 11,892 | 1.52 | 2.54 | 0 | 19 |
| age | 11,888 | 51.62 | 11.30 | 25 | 94 |
| exp | 9,479 | 7,125,574.00 | 5,201,119.00 | 535 | 27,462,362 |
| status | 11,892 | 0.49 | 0.62 | 0 | 2 |
| vote | 11,892 | 54,787.54 | 39,815.58 | 177 | 210,515 |
| voteshare | 11,892 | 27.34 | 19.21 | 0.10 | 95.30 |
| eligible | 10,773 | 351,536.30 | 66,499.14 | 191,241 | 495,212 |
| turnout | 10,773 | 59.75 | 7.10 | 42.09 | 83.80 |
| seshu_dummy | 11,892 | 0.09 | 0.29 | 0 | 1 |
ggplot() and
geom_bar()| Geometric object | What you can do |
ggplot() |
Prepare a canvas |
geom_bar() |
Draw a bar chart |
year (1996, 2000, 2003,…, 2026)hrtable(), check the number of candidates in each
election
1996 2000 2003 2005 2009 2012 2014 2017 2021 2024 2026
1261 1199 1026 989 1139 1294 959 936 857 1113 1119
year (x-axis), and the number of
candidates (y-axis)hr contains year, but hr does
not have the variable representing the number of candidatesx in
geom_bar(aes())y in
geom_bar(aes())ggplot2} automatically calculates and showsit in a bar
chartgeom_bar(aes(x = year))labs() layer, you can put a label on
x-axis and y-axishr %>%
ggplot() +
geom_bar(aes(x = year)) +
labs(x = "Election Year",
y = "The number of candidates") +
ggtitle("The number of candidates in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") year is numericyear by using
str() num [1:11892] 1996 1996 1996 1996 1996 ...
year if
numericR understands year as a continuous
variableSolution
class of year from
numeric to factorclass of year Factor w/ 11 levels "1996","2000",..: 1 1 1 1 1 1 1 1 1 1 ...
class of year is changed to
factorhr %>%
ggplot() +
geom_bar(aes(x = year)) +
labs(x = "Election Year",
y = "The number of candidates") +
ggtitle("The number of candidates in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3")
- You can save this bar chart with an appropriate name on it, like
bar_plot1
- If this is the case, then you type as follows:
bar_plot1 <- hr %>%
ggplot() +
geom_bar(aes(x = year)) +
labs(x = "Election Year",
y = "The number of candidates") +
ggtitle("The number of can didates in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") See 5. How to save graphs for how to save
graphs
If you want to output the graph, just type the object name, in
this case, bar_plot1 in a chunk and knit it
What we can see from this graph ・The number of candidates in Japan’s lower house elections has been decreasing (except 2009 and 2012)
year (1996, 2000, 2003,…, 2026)You use the data frame, hr
Using table(), check the number of candidates in
each election
Assign year (x-axis), and the average
number of candidates in each electoral district and in each election
(y-axis)
hr contains year, but hr
does not have the variable representing the average number of candidates
in each electoral district and in each election
You can calculate this variable by using group_by()
and save its results as ave_nocand1
# A tibble: 517 × 3
# Groups: year [11]
year ku ave_nocand1
<fct> <chr> <dbl>
1 1996 aichi 6.33
2 1996 akita 3.4
3 1996 aomori 3.93
4 1996 chiba 4.75
5 1996 ehime 3.57
6 1996 fukui 4.17
7 1996 fukuoka 3.90
8 1996 fukushima 3.67
9 1996 gifu 3.78
10 1996 gunma 3.84
# ℹ 507 more rows
ave_nocand1 in each
election and save it as ave_nocand2# A tibble: 11 × 2
year ave_nocand2
<fct> <dbl>
1 1996 4.11
2 2000 3.93
3 2003 3.45
4 2005 3.40
5 2009 3.86
6 2012 4.20
7 2014 3.23
8 2017 3.27
9 2021 3.00
10 2024 3.75
11 2026 3.97
geom_bar() and map
aes() as follows:x-axis: x = yeary-axis: y = ave_nocand2geom_bar(aes(x = year, y = ave_nocand2))x and y, you need to
assign as stat = "identity" inside of
geom_bar() and out of aes()labs() layer, you can put a label on
x-axis and y-axisdf1 %>%
ggplot() +
geom_bar(aes(x = year,
y = ave_nocand2),
stat = "identity") +
labs(x = "Election Year", y = "The average number of candidate in each district and in each election") +
ggtitle("The average number of candidates in each district (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") What you can see from this bar chart
・ The number of candidates in each sigle-member-district has been
decreasing over time since 1996 (except in 2009 and 2012)
- Japanese lower house election seems to be getting closer to a
two-candidate election
status (incumbent, challenger, and former-incumbent) in
Japanese lower house elections (1996-2026)status: (challenger = 0, incumbent = 1,
former-incumbent = 2)N : The number of candidates by statusdfstatus, by using table()
0 1 2
6808 4315 769
x-axis: statusy-axis: Ndf contains status, but df
does not have Nx in geom_bar(aes())y in
geom_bar(aes())ggplot2} automatically calculates and shows it in a
bar chartgeom_bar(aes(x = status))labs() layer, you can put a label on
x-axis and y-axishr %>%
ggplot() +
geom_bar(aes(x = status)) +
labs(x = "Candidate status",
y = "The number of candidates") +
ggtitle("The number of candidates by stasus in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") x-axis shows 0, 1, and 2 showing candidate’s
statuscase_when(), you re-code
statusstatus_J as a new variable to df and
override it as df2df2 <- hr %>%
mutate(status_J = case_when(status == "0" ~ "challengers",
status == "1" ~ "incumbents",
TRUE ~ "former-incumbents"))x = status, you need to type
x = status_J in mappingdf2 %>%
ggplot() +
geom_bar(aes(x = status_J)) +
labs(x = "Candidate's status",
y = "The number of candidates") +
ggtitle("The number of candidates by stasus in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") How to fix the garbled characters in a
graph
For Windows users: Add the following R code
theme_bw(base_family = "HiraKakuProN-W3")
For Mac users: Add the following R code
theme_bw(base_family = "HiraKakuProN-W3")
factor() mutate(), you change the class of
status_j to factor and then pass it to
ggplot() → Change the order by hand:
levels = c("incumbents", "challengers", "former-incumbents")df2 %>%
mutate(status_J = factor(status_J,
levels = c("incumbents", "challengers", "former-incumbents"))) %>%
ggplot() +
geom_bar(aes(x = status_J)) +
labs(x = "Candidate status",
y = "The number of candidates") +
ggtitle("The number of candidates by stasus in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") fct_inorder() fct_inorder(), you need to install
{forcats} tidyverse} includes {forcats}tidyverse}, then you do not have to
install {forcats}.fct_inorder() change the class of variables in the
parenthesis to factor and put them in orderstatus_J[1] "challengers" "challengers" "challengers"
[4] "challengers" "incumbents" "former-incumbents"
status_J is incumbents,
former-incumbent, challengersstatus_J, then you use
fct_inorder() df2 %>%
mutate(status_J = fct_inorder(status_J)) %>%
ggplot() +
geom_bar(aes(x = status_J)) +
labs(x = "Candidate status", y = "The number of candidates") +
ggtitle("The number of candidates by stasus in Japan's lower house elections (1996-2026)") +
theme_bw(base_family = "HiraKakuProN-W3") Usually, a bar chart has x-axis and
y-axis
A bar includes the information of a HR election
(x-axis) and the number of candidates
(y-axis)
The number of dimentions means the amount of information
This information is the number of arguments within
aes()
Let’s draw a bar chart of the number of candidates by party
(seito) in the 2021 HR election
[1] "N党" "立憲" "自民" "国民" "維新" "共産" "れい" "無所" "諸派" "社民"
[11] "公明"
seito to factor
and assign the order of values of seito as you likeHow to
assign the order of the values in
seito
・For instance, suppose you want to arrange, 自民、立憲、共産 in order,
you assign as follows:
mutate(seito = factor(seito,
levels = c("自民", "立憲", "共産")))
N)N) by gender and
partyres_1) on the outcomeres_1 %>%
ggplot() +
geom_bar(aes(x = seito,
y = N),
stat = "identity") +
ggtitle("The number of candidates by party in the 2021 HR Election)") +
theme_bw(base_family = "HiraKakuProN-W3") x-axis: Party names seitoy-axis: The number of candidates (N)fill = gendergender) to the bar chart
aboveaes()fillcolor - You can customize the type of the framer border
with linetypealphsfillfill = gender within aes()
を追加するres_1 %>%
ggplot() +
geom_bar(aes(x = seito,
y = N,
fill = gender),
stat = "identity") +
ggtitle("The number of candidates by party & gender in the 2021 HR Election)") +
theme_bw(base_family = "HiraKakuProN-W3") position = "dodge"position = "dodge" within
geom_bar()position = "dodge" OUT OF aes()res_1 %>%
ggplot() +
geom_bar(aes(x = seito,
y = N,
fill = gender),
stat = "identity",
position = "dodge") + # position = "dodge" is mapped out of aes()
ggtitle("The number of candidates by party & gender in the 2021 HR Election)") +
theme_bw(base_family = "HiraKakuProN-W3") theme(legend.position = "bottom")theme() enables us to precisely customize the outlook
of a graphlegend.position = "bottom" within
theme()"right""top", "left", and "none"res_1 %>%
ggplot() +
geom_bar(aes(x = seito,
y = N,
fill = gender),
stat = "identity",
position = "dodge") +
ggtitle("The number of candidates by party & gender in the 2021 HR Election)") +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(legend.position = "bottom") facet_wrap()facet_wrap()facet_wrap(~ variable name)res_1 %>%
ggplot() +
geom_bar(aes(x = gender,
y = N),
stat = "identity") +
ggtitle("The number of candidates by party & gender in the 2021 HR election") +
theme_bw(base_family = "HiraKakuProN-W3") +
facet_wrap(~ seito) gender with seito in
mapping aes() and replace seito with
gender in mapping facet_wrap() and draw the
following bar chart.res_1 %>%
ggplot() +
geom_bar(aes(x = seito,
y = N),
stat = "identity") +
ggtitle("The number of candidates by party & gender in the 2021 HR election") +
theme_bw(base_family = "HiraKakuProN-W3") +
facet_wrap(~ gender) theme(axis.text.x = element_text(angle = XX, vjust = X, hjust = X)x-axisare too long overlapping
one anotherx-axis so that you can see them without overlapping one
anothertheme(axis.text.x= element_text() as a new
layer to get this doneangle = ...angle = 30res_1 %>%
ggplot() +
geom_bar(aes(x = seito,
y = N),
stat = "identity") +
facet_wrap(~ gender) +
labs(x = "Political Party",
y = "The number of candidates") +
ggtitle("The number of candidates by party & gender in the 2021 HR election") +
theme_minimal() +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(axis.text.x= element_text(angle = 30, vjust = 1, hjust = 1),
panel.grid.major.x = element_blank()) fill = variable name within aes(),
then you can add a new layerelec_result, and then draw a bar
chart with ggplot()res_1 %>%
mutate(elec_result = if_else(wl == "0", "lose", "win")) %>%
ggplot() +
geom_bar(aes(x = seito,
y = N,
fill = elec_result),
stat = "identity") +
facet_wrap(~ gender) +
labs(x = "Political party", y = "The number of candidates") +
ggtitle("The number of candidates by party & win/lose in the 2021 HR election") +
theme_minimal() +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(axis.text.x = element_text(angle = 40,
vjust = 1,
hjust = 1),
panel.grid.major.x = element_blank()) +
theme(legend.position = "bottom")x-asis and y-axisx-asix is too long overlapping one
another, you should simply swich x-asis and
y-axisres_1 %>%
ggplot() +
geom_bar(aes(x = N,
y = seito),
stat = "identity") +
facet_wrap(~ gender) +
labs(x = "The number of candidates", y = "Politial party") + # ラベル修正
ggtitle("The number of candidates by party & win/lose in the 2021 HR election") +
theme_minimal() +
theme_bw(base_family = "HiraKakuProN-W3") x-axis and y-axis:
coord_flip()axes by adding
coord_flip()geom_text(aes(label = variable name))Suppose you want to display numbers on the following bar
chart
The number of numbers (values) you want to displays on bars is
11
The number of candidates these 11 parties nominated
Check the data frame res_1
Check how you made
res_1
df21 <- df %>%
filter(year == 2021) %>% # Select the 2021 HR election data
drop_na(seito) %>% # Drop missing values in seito
mutate(seito = factor(seito, # change the class of seito to factor and arrange in order you want
levels = c("自民",
"立憲",
"共産",
"維新",
"無所",
"N党",
"国民",
"れい",
"公明",
"諸派",
"社民")))res_1res_1res_1, you calculate the number of candidates
each party nominated (=
party_cand) and name it res_2res_2geom_text(aes(label = party_cand), you can
display the numbers on barsres_2 %>%
ggplot(aes(x = seito,
y = party_cand)) +
geom_bar(aes(),
stat = "identity",
position = position_dodge(width = 0.9)) +
geom_text(aes(label = party_cand),
vjust = 1.2,
colour = "yellow",
position = position_dodge(width = 0.9),
size = 3) +
ggtitle("The number of candidates by party in the 2021 HR Election") +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(legend.position = "bottom") res_1res_1, you calculate the number of candidates 11
parties nominated by gender (=
total) and name it res_3res_3geom_text(aes(label = total), you can display
the numbers on barsres_3 %>%
ggplot(aes(x = seito,
y = total,
fill = gender)) +
geom_bar(aes(),
stat = "identity",
position = position_dodge(width = 0.9)) +
geom_text(aes(label = total),
vjust = 1.2,
colour = "white",
position = position_dodge(width = 0.9),
size = 3) +
ggtitle("The number of candidates by party & gender in the 2021 HR Election") +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(legend.position = "bottom") vjust = 1.2colour = "white" to
colour = "black"res_3 %>%
ggplot(aes(x = seito,
y = total,
fill = gender)) +
geom_bar(aes(),
stat = "identity",
position = position_dodge(width = 0.9)) +
geom_text(aes(label = total),
colour = "black", # Change the color of the number
position = position_dodge(width = 0.9),
size = 3) +
ggtitle("The number of candidates by party & gender in the 2021 HR Election") +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(legend.position = "bottom") position = "stack"Suppose you want to display numbers on the following bar
chart
The number of numbers (values) you want to displays on bars is
22
The 22 values are the number of candidates 11 parties nominated
in the 2021 HR election by gender
Check the data frame res_1
Using res_1, you calculate the number of candidates
11 parties nominated by gender (=
total) and name it res_4
res_4geom_text(aes(label = total), you can display
the numbers on barsres_4 %>%
ggplot(aes(x = seito,
y = total,
fill = gender)) +
geom_bar(aes(),
stat = "identity",
position = "stack") + # Change to [position = "stack"]
geom_text(aes(label = total),
colour = "black",
position = "stack", # Change to [position = "stack"]
size = 3) +
ggtitle("The number of candidates by party & gender in the 2021 HR Election") +
theme_bw(base_family = "HiraKakuProN-W3") +
theme(legend.position = "bottom") | Type of format | Extension | File size | Quality |
|---|---|---|---|
| Vector | .pdf (recommended) .svg |
large | Good |
| Bitmap | .png (recommended) .bmp .jpg .jpeg |
small | OK |
bar_plot_1) with Vector
and png formatggsave(), you save a graph made on
ggplot2bar_plot1 (whatever name
you like)Figs in
you RProject folderragg}ggsave(filename = "Figs/plot1.png", # Assign where you want to save your graph and name it
plot= bar_plot1, # The name of graph you made
width= 6, # Inch
height= 3, # Inch
dpi = 400, # Assign graph resolution
device= ragg::agg_png) # Avoid the garbled characters in a graphbar_plot1plot1.pngFigs in your RProject folder{ragg} enables us to avoid the garbled characters in a
graphQ6.1:
In reference to 3.1 Draw a simple bar chart (1), draw a bar
chart of the number of male candidates between the
lower house elections between 1996 and 2021 in Japan.
Q6.2:
In reference to 3.1 Draw a simple bar chart (1), draw a bar
chart of the number of female candidates between the
lower house elections between 1996 and 2021 in Japan.
Q6.3:
In reference to 3.5.3 Dodge bars, draw a bar chart of the
number of candidates dodged by gender between the lower
house elections between 1996 and 2021 in Japan.
Q6.4(Advance):
In reference to 3.8 Add a new layer to facet, draw a bar
chart of the number of winners (wl = 1 & 2) and losers
(wl = 0) by party faceted by candidate status
(status) in the 2021 HR election in Japan.
・winners include both those who won in a single-member-district
(wl = 1) and zombie winners (wl = 2)
Q6.5(Advance):
In reference to
4.2 A bar chart with numbers displayed (dodge), draw a bar
chart of the number of single-member-district winners
(wl = 1), zombie winners (wl = 2), and losers
(wl = 0) by party faceted by candidate status
(status) in the 2021 HR election in
Japan.