Python&R: Learning Python & R on RStudio ver.2

Last Updated on August 30, 2022 by shibatau

The first 5 lines are added in the scripts in I.1.Python.

I.2 is added.

I. Reading a CSV dataset and create a bar chart

1.Python

The scripts:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# read the data
df = pd.read_csv("https://pastebin.com/raw/cSZ8pYWh")
## calculate means of each nationality
# in a usual way
df[['english', 'japanese', 'nationality']].groupby(by = 'nationality').mean().round(1)
# using () to make the scripts easy to read
(df.
 filter(['english', 'japanese', 'nationality']).
 groupby(by = 'nationality').
 mean().
 round(1)
)
# create a bar chart
df_grouped = df[['english', 'japanese', 'nationality']].groupby(by = 'nationality').mean().round(1)
df_grouped.reset_index(inplace=True)
# english
sns.barplot(x = 'nationality',
            y = 'english',
            data = df_grouped).set(title='English by nationality')
plt.show()
# japanese
sns.barplot(x = 'nationality',
            y = 'japanese',
            data = df_grouped).set(title='Japanese by nationality')
plt.show()

2. R

The scripts:

library(tibble) # for a modified version of a data frame 
library(dplyr)
library(readr) # for reading data from URL
library(ggplot2) # for creating charts
df <- read_csv("https://pastebin.com/raw/cSZ8pYWh")
df_grouped <- df |>
  select(english, japanese, nationality) |> 
  group_by(nationality) |>
  summarise(av_english = mean(english),
            av_japanese = mean(japanese))
  
g1 <- ggplot(df_grouped, aes( x=nationality, y=av_english)) +
  geom_bar(stat="identity") +
  labs(title = "English score by nationality")
g1

g2 <- ggplot(df_grouped, aes( x=nationality, y=av_japanese)) +
  geom_bar(stat="identity") +
  labs(title = "Japanese score by nationality")
g2

To be continued.

About shibatau

I was born and grown up in Kyoto. I studied western philosophy at the University and specialized in analytic philosophy, especially Ludwig Wittgenstein at the postgraduate school. I'm interested in new technology, especially machine learning and have been learning R language for two years and began to learn Python last summer. Listening toParamore, Sia, Amazarashi and MIyuki Nakajima. Favorite movies I've recently seen: "FREEHELD". Favorite actors and actresses: Anthony Hopkins, Denzel Washington, Ellen Page, Meryl Streep, Mia Wasikowska and Robert DeNiro. Favorite books: Fyodor Mikhailovich Dostoyevsky, "The Karamazov Brothers", Shinran, "Lamentations of Divergences". Favorite phrase: Salvation by Faith. Twitter: @shibatau

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.