<jupyter_start><jupyter_text>--- 
 
    Graphical EDA  [2008 US swing state election result]
 


--- 
  
    
  

  __Part - A__ --- 
 
    Swing State 


--- __Clone the repository__<jupyter_code>! git clone https://github.com/mohd-faizy/CAREER-TRACK-Data-Scientist-with-Python.git<jupyter_output>Cloning into 'CAREER-TRACK-Data-Scientist-with-Python'...
remote: Enumerating objects: 116, done.[K
remote: Counting objects: 100% (116/116), done.[K
remote: Compressing objects: 100% (96/96), done.[K
remote: Total 1973 (delta 51), reused 69 (delta 19), pack-reused 1857[K
Receiving objects: 100% (1973/1973), 204.60 MiB | 39.71 MiB/s, done.
Resolving deltas: 100% (703/703), done.
Checking out files: 100% (840/840), done.<jupyter_text>__Change the current working directory__<jupyter_code># import os module 
import os 
   
# to specified path 
os.chdir('/content/CAREER-TRACK-Data-Scientist-with-Python/22_Statistical-Thinking-in-Python-[Part -1]/_datasets') 
  
# varify the path using getcwd() 
cwd = os.getcwd() 
  
# print the current directory 
print("Current working directory is:", cwd)
ls<jupyter_output>2008_all_states.csv    belmont.csv  michelson_speed_of_light.csv
2008_swing_states.csv  iris.csv<jupyter_text>__Exploratory data analysis (EDA)__

__<NAME>'s Comments on EDA -:__ "Often times **EDA** is too time consuming, so it is better to jump right in and do our **hypothesis** tests."

That statement is pretty absurd. If we don't have time to do EDA, we really don't have time to do **hypothesis** tests. And we should always do **EDA first**.

__“Exploratory data analysis can never be the whole story, but nothing else can serve as the foundation stone.”__ — _<NAME>_<jupyter_code># importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Reading the dataframe in Pandas
df_swing = pd.read_csv('2008_swing_states.csv')
df_swing.head()
print('Total Democrat votes {}'.format(df_swing.dem_votes.sum()))
print('Total Republican votes {}'.format(df_swing.rep_votes.sum()))
# Percentage vote count Swing state
tvc = df_swing.total_votes.sum()
tdv = (df_swing.dem_votes.sum()/tvc)*100
trv = (df_swing.rep_votes.sum()/tvc)*100

# creating the dataset 
data = {'Democrat':tdv, 
        'Republican':trv}

keys = list(data.keys()) 
values = list(data.values()) 

# Set default Seaborn style
sns.set()

# set the plot size
fig = plt.figure(figsize = (10, 5)) 

# creating the bar plot 
plt.bar(keys, values, color=['tab:blue', 'tab:red'], width = 0.5) 
  
plt.xlabel("Political Party") 
plt.ylabel("Votes Percent")
plt.title("Percent Vote Counts") 
plt.show() 

# Vote Percent in 2008 election
print('Total Vote Percantage of Democrat in 2008 is {0:.2f} percent'.format(tdv))
print('Total Vote Percantage of Republican in 2008 is {0:.2f} percent'.format(trv))
df_swing.isna().sum()
print(df_swing.columns )
print(df_swing.state.value_counts())
print(df_swing.shape)
df_swing.describe()
# Democratic share
df_swing[['state', 'county', 'dem_share']].head()<jupyter_output><empty_output><jupyter_text>__Histograms__<jupyter_code>sns.set()
_ = plt.hist(df_swing['dem_share'])
_ = plt.xlabel('percent of vote for Obama')
_ = plt.ylabel('number of counties')

plt.show()
# Set default Seaborn style
sns.set()

# Histograms with different binning
_ = plt.hist(df_swing['dem_share'], bins=20)
_ = plt.xlabel('percent of vote for Obama')
_ = plt.ylabel('number of counties')
plt.show()
bin_edges = [0, 10, 20, 30, 40, 50,
60, 70, 80, 90, 100]

sns.set()
_ = plt.hist(df_swing['dem_share'], bins=bin_edges)
_ = plt.xlabel('percent of vote for Obama')
_ = plt.ylabel('number of counties')


plt.show()
# display records only with states
ohio = df_swing.loc[df_swing["state"] == "OH"]
penn = df_swing.loc[df_swing["state"] == "PA"]
florida = df_swing.loc[df_swing["state"] == "FL"]

oh = ohio['dem_share']
pa = penn['dem_share']
fl = florida['dem_share']

# Set default Seaborn style
sns.set()

plt.figure(figsize=(12, 7))

# Histograms with different binning
plt.hist(oh, label='OH', alpha = 0.7)
plt.hist(pa, label='PA', alpha = 0.6)
plt.hist(fl, label='FL', alpha = 0.4)
plt.xlabel('percent of vote for Obama')
plt.ylabel('number of counties')
plt.legend()
plt.show()
# display records only with states
ohio = df_swing.loc[df_swing["state"] == "OH"]
penn = df_swing.loc[df_swing["state"] == "PA"]
florida = df_swing.loc[df_swing["state"] == "FL"]

oh = (ohio['dem_share'].sum()/df_swing.dem_share.sum())*100
pa = (penn['dem_share'].sum()/df_swing.dem_share.sum())*100
fl = (florida['dem_share'].sum()/df_swing.dem_share.sum())*100

# creating the dataset 
data = {'OHIO':oh, 
        'PENN':pa,
        'FLORIDA':fl}

keys = list(data.keys()) 
values = list(data.values()) 

# Set default Seaborn style
sns.set()

# set the plot size
fig = plt.figure(figsize = (10, 5)) 

# creating the bar plot 
plt.bar(keys, sorted(values), color=['tab:green', 'tab:blue', 'tab:red'], width = 0.5) 
  
plt.xlabel("Vote in swing states") 
plt.ylabel("Percentage vote count in swing states")
plt.title("Percent Vote Counts") 
plt.show()

print('ohio vote percent {0:.2f}'.format((ohio['dem_share'].sum()/df_swing.dem_share.sum())*100))
print('penn vote percent {0:.2f}'.format((penn['dem_share'].sum()/df_swing.dem_share.sum())*100))
print('Florida vote percent {0:.2f}'.format((florida['dem_share'].sum()/df_swing.dem_share.sum())*100))<jupyter_output><empty_output><jupyter_text>__Swarm Plot__ $\color{red}{\textbf{Note:}}$ 

The **same data set can look different depending on how the bins are chosen**. And choice of bins is in many ways arbitrary. This leads to **Binning bias**
that is we might interpret our plot differently for two different choices of bin number.

>An **additional problem with histograms** is that we are not plotting all of the data. We are sweeping the data into bins, and losing their actual values.

To remedy these problems we can make a bee swarm plot, also called a **swarm plot**.  In the IPython Shell, you can use `sns.swarmplot`? or help(`sns.swarmplot`) for more details on how to make bee swarm plots using seaborn.<jupyter_code>plt.figure(figsize=(12, 7))

# Create bee swarm plot with Seaborn's default settings
_ = sns.swarmplot(x='state', y='dem_share', data=df_swing)

# Label the axes
_ = plt.xlabel('state')
_ = plt.ylabel('percent of vote for Obama')

# Show the plot
plt.show()<jupyter_output><empty_output><jupyter_text>__Empirical cumulative distribution function (ECDF)__ The **bee swarm** plot has a r**eal problem**. the **edges have overlapping data points**, which was necessary in order to fit all points onto the plot.

We are now obfuscating data. So, using a bee **swarm plot** here is **not** the best option. As an alternative, **Empirical cumulative distribution function (ECDF).**

Sometimes the **observations** in a collected data sample **do not fit** any known **probability distribution** and cannot be easily forced into an existing distribution by __data transforms__ or __parameterization__ of the distribution function.Instead, an __Empirical probability distribution__ must be used.

---
There are __two main types of probability distribution functions__ we may need to sample; they are:

- __Probability Density Function (PDF)__
    - The __PDF__ returns the expected probability for observing a value. For __discrete data__, the __PDF__ is referred to as a __Probability Mass Function (PMF)__.
- __Cumulative Distribution Function (CDF)__
    - The __CDF__ returns the expected probability for observing a value __less than or equal to a given value.
---
An __Empirical probability density function__ can be __fit__ and used for a data sampling using a __Non-Parametric density estimation__ method, such as __Kernel Density Estimation (KDE)__.

>__kernel density estimation ( KDE)__ is a __non-parametric__ way to estimate the __Probability Density Function__ of a random variable. Kernel density estimation is a fundamental __Data Smoothing__ problem where inferences about the population are made, based on a __finite data sample__.


>An **ECDF** is an estimator of the **Cumulative Distribution Function**. The ECDF essentially allows you to plot a feature of our data in order from *least to greatest and see the whole feature as if is distributed across the data set*.

The **EDF is calculated** by ordering all of the **unique observations** in the data sample and calculating the **Cumulative probability** for each as the number of observations less than or equal to a given observation divided by the total number of observations.

  __CDF vs ECDF__

**CDF** is a **hypothetical model** of a distribution, the **ECDF models** empirical (i.e. **observed**) data. To put this another way, the ECDF is the **probability distribution** you would get if you sampled from your sample, instead of the population.<jupyter_code># 2008 US swing state election ECDF
import numpy as np

#ECDF
x = np.sort(df_swing['dem_share'])
y = np.arange(1, len(x)+1) / len(x)

plt.figure(figsize=(12, 7))

# Ploting ECDF
_ = plt.plot(x, y, marker='.', linestyle='none')
_ = plt.xlabel('percent of vote for Obama')
_ = plt.ylabel('ECDF')
plt.margins(0.02) # Keeps data off plot edges
plt.show()<jupyter_output><empty_output><jupyter_text>__Graph Interpretation__

- 20% of counties had 36% or less vote for Obama.
- 75% of counties had less than half vote for Obama.<jupyter_code># display records only with states
ohio = df_swing.loc[df_swing["state"] == "OH"]
penn = df_swing.loc[df_swing["state"] == "PA"]
florida = df_swing.loc[df_swing["state"] == "FL"]

oh = ohio['dem_share']
pa = penn['dem_share']
fl = florida['dem_share']

# Comparison of ECDFs
a = np.sort(oh)
b = np.sort(pa)
c = np.sort(fl)

x = np.arange(1, len(a)+1) / len(a)
y = np.arange(1, len(b)+1) / len(b)
z = np.arange(1, len(c)+1) / len(c)

plt.figure(figsize=(12, 7))

# Ploting ECDF
plt.plot(a, x, marker='o', linestyle='none', label='OH')
plt.plot(b, y, marker='o', linestyle='none', label='PA')
plt.plot(c, z, marker='o', linestyle='none', label='FL')

plt.xlabel('percent of vote for Obama')
plt.ylabel('ECDF')
plt.margins(0.02) # Keeps data off plot edges
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>__Summary Statistics: The sample Mean and Median__ [Quantitative exploratory data analysis] >**Outliers:**
Data points whose value is far greater or less than most of
the rest of the data. >$\color{red}{\textbf{Note:}}$ `inf` used for setting a variable with an infinitely large value. __The Median:__

Sort the the data and choosing the datum in the __Middle__. Because it is derived from the __ranking of sorted data__, and not on the values of the data, the __Median is immune to data that take on extreme values__.

- The median is a special name for the __50th percentile__.

>$\color{red}{\textbf{Note:}}$
An **outlier** can significantly affect the value of the __Mean__, but not the **Median**.<jupyter_code># vote shares
vote_share_PA = df_swing.loc[df_swing["state"] == "PA"]
np.mean(vote_share_PA)
# democratic vote share in PA 
print('Mean:{}'.format(np.mean(vote_share_PA.dem_share)))
print('Median: {}'.format(np.median(vote_share_PA.dem_share)))
df_swing.county.describe()
# Test if pattern or regex is contained within a string of a Series or Index.
df_swing.county.str.contains('ut').values # for Utha county
# Mean and median Vote share for washington County
wash_c = df_swing.loc[df_swing["county"] == "Washington County"]
print(np.mean(wash_c))<jupyter_output>total_votes    42660.000000
dem_votes      16741.000000
rep_votes      25316.333333
dem_share         26.780000
dtype: float64<jupyter_text>__Combine Box and Swarmplot__<jupyter_code>plt.figure(figsize=(12, 7))

# Create bee swarm plot with Seaborn's default settings
_ = sns.boxplot(x='state', y='dem_share', data=df_swing, whis=np.inf) 
_ = sns.swarmplot(x='state', y='dem_share', data=df_swing, color=".2")

# Label the axes
_ = plt.xlabel('state')
_ = plt.ylabel('percent of vote for Obama')

# Show the plot
plt.show()
# Percentile
np.percentile(df_swing['dem_share'], [25, 50, 75])<jupyter_output><empty_output><jupyter_text>**Variance** and **standard deviation**


    
 >__Variance__ is the mean **squared distance** of the data from their **mean**. Informally, a measure of the ***spread of data***.

$$ variance = \dfrac{1}{n}\sum^{n}_{i=1}(x_i - \bar{x})^2 $$ >__Standard Deviation__  is a measure that is used to **quantify** the amount of ***variation*** or ***dispersion*** of a set of data values.

$$ Standard Deviation = \sqrt{\dfrac{\sum(x_i - \bar{x})^2}{n - 1}} $$<jupyter_code># Display records only with states 
florida = df_swing.loc[df_swing["state"] == "FL"]

# Computing the variance
print('Variance {0:.2f}'.format(np.var(florida.dem_share)))

# Computing the Standard Deviation
print('Standard Deviation {0:.2f}'.format(np.std(florida.dem_share)))<jupyter_output>Variance 147.44
Standard Deviation 12.14<jupyter_text>**Covariance** and the **Pearson correlation coefficient**<jupyter_code># Total swing votes
total_votes = df_swing.total_votes

# Democrates Share
demcrats_share = df_swing.dem_share

print('mean total votes {0:.2f}'.format((total_votes/1000).mean()))
print('mean percent for obama {0:.2f}'.format(demcrats_share.mean()))

# Set default Seaborn style
sns.set()

# figure size
plt.figure(figsize=(12, 7))

# vertical mean line 
plt.axvline((total_votes/1000).mean(), color='red',
            linestyle='dashed', linewidth=1,
            label='mean total votes')

# horizontal mean line
plt.axhline(demcrats_share.mean(), color='k',
            linestyle='dashed', linewidth=1,
            label='mean percent for obama')
# Plot
_ = plt.plot(total_votes/1000, demcrats_share, marker='o', linestyle='none')
_ = plt.xlabel('total votes (thousands)')
_ = plt.ylabel('percent of vote for Obama')
_ = plt.legend()
plt.show()<jupyter_output>mean total votes 90.42
mean percent for obama 43.76<jupyter_text>***The twelve most populous counties all voted for Obama, and that most of the counties with small populations voted for McCain.*** The mean total votes. We can compute these differences for each data point.

The **covariance** is the mean of the product of these differences. If x and y both tend to be above, or both below their respective means together, as they are in this data set, then the **covariance is positive** i.e (positively correlated) when **x is high**, so is **y**; when the county is **populous**, it has more votes for Obama.

Conversely, if **x is high** while **y is low**, the covariance is negative, and the data are **negatively correlated**, or **anticorrelated**, which is not the case for this data set.


  __Covariance__ it is the measure of how the two quantities vary together.- Covariance is a measure of the relationship between two random variables and to what extent, they change together. Or we can say, in other words, it defines the changes between the two variables, such that change in one variable is equal to change in another variable.- If the covariance for any two variables is positive, that means, both the variables move in the same direction. Here, the variables show similar behaviour.$$ covariance = \dfrac{1}{n}\sum^{n}_{i=1}(x_i - \bar{x})(y_i - \bar{y})$$<jupyter_code># Compute the covariance matrix: covariance_matrix
covariance_matrix = np.cov((total_votes/1000), demcrats_share )

sns.heatmap(covariance_matrix,
                 cbar=True,
                 annot=True,
                 square=True,
                 fmt='.2f',
                 annot_kws={'size': 12}
                 )

# Print covariance matrix
print(covariance_matrix)

# Extract covariance of length and width of petals: petal_cov
petal_cov = covariance_matrix[0, 1]

# Print the length/width covariance
print(petal_cov)<jupyter_output>[[20245.10393632   817.30936184]
 [  817.30936184   114.76344739]]
817.3093618405288<jupyter_text>__Pearson correlation coefficient__


We can compute the **covariance** using built-in NumPy functions. However, if we want to have a more **generally applicable measure** of **how two variables depend on each other**, we want it to be **dimensionless**, that is to not have any units.

So, we can divide the covariance by the ***standard deviations of the x and y variables***. This is called the Pearson correlation coefficient, usually denoted by the Greek letter rho.  ___Why is the Pearson correlation coefficient important?___

It helps in knowing **how strong the relationship between the two variables** is. Not only the presence or the absence of the correlation between the two variables is indicated using the Pearson Correlation Coefficient but it also determines the **exact extent to which those variables are correlated**.


The **Pearson coefficient correlation** has a **high statistical significance**. It looks at the relationship between two variables. It seeks to draw a line through the data of two variables to show their relationship. The relationship of the variables is measured with the help Pearson correlation coefficient calculator. $$ \begin{align} \rho &= \text{Pearson correlation} = \dfrac{\text{covariance}}{(\text{std of x})(\text{std of y})} \\ &= \dfrac{\text{variability due to codependence}}{\text{independent variability}} \end{align}$$<jupyter_code>def pearson_r(x, y):
    """Compute Pearson correlation coefficient between two arrays
    
    Args:
        x: arrays
        y: arrays
        
    returns:
        r: int
    """
    # Compute correlation matrix: corr_mat
    corr_mat = np.corrcoef(x, y)
    
    # Return entry[0, 1]
    return corr_mat[0, 1]

# Compute Pearson correlation coefficient for I. versicolor: r
r = pearson_r((total_votes/1000), demcrats_share)

# Print the result
print(r)
ls<jupyter_output>2008_all_states.csv    belmont.csv  michelson_speed_of_light.csv
2008_swing_states.csv  iris.csv<jupyter_text>__Part - B__ 
--- 
 
    All State 


---<jupyter_code># Reading the dataframe in Pandas
df_all_state = pd.read_csv('2008_all_states.csv')
df_all_state.head(-10)
print(df_swing.shape)
print(df_all_state.shape)
df_all_state.columns
df_all_state.describe()
df_all_state.info()
df_all_state.value_counts()
df_all_state.state.unique()
# Using ggplot style
plt.style.use('ggplot')

# figure size
plt.figure(figsize=(15, 7), facecolor='lightgrey')

df_all_state.state.value_counts().plot(kind='bar')
# Percentage vote count in all state
all_vote_Count = df_all_state.total_votes.sum()
all_dem_v = (df_all_state.dem_votes.sum()/all_vote_Count)*100
all_rep_v = (df_all_state.rep_votes.sum()/all_vote_Count)*100

# creating the dataset 
data = {'Democrat':all_dem_v, 
        'Republican':all_rep_v}

keys = list(data.keys()) 
values = list(data.values()) 

# Set default Seaborn style
plt.style.use('ggplot')

# set the plot size
fig = plt.figure(figsize = (10, 5)) 

# creating the bar plot 
plt.bar(keys, values, color=['tab:blue', 'tab:red'], width = 0.5) 
  
plt.xlabel("Political Party") 
plt.ylabel("Votes Percent")
plt.title("Percent Vote Counts") 
plt.show() 

# Vote Percent in 2008 election
print('All State Vote Percantage of Democrat in 2008 is {0:.2f} percent'.format(all_dem_v))
print('All State Vote Percantage of Republican in 2008 is {0:.2f} percent'.format(all_rep_v))
# Percantage Vote share using seaborn
rep = (df_all_state.rep_votes.sum()/df_all_state.total_votes.sum())*100
dem = (df_all_state.dem_votes.sum()/df_all_state.total_votes.sum())*100

data ={'Republican': rep,
       'Democrate': dem}

keys = list(data.keys()) 
values = list(data.values()) 

# set the plot size
fig = plt.figure(figsize = (12, 7), facecolor='lightgray')

sns.barplot(keys,values)
import matplotlib.pyplot as plt
import seaborn as sns

# Set default Seaborn style
sns.set()

# figure size
plt.figure(figsize=(12, 7), facecolor='lightgrey')

_ = sns.boxplot(x=df_all_state.east_west, y=df_all_state.dem_share, data=df_all_state)
_ = plt.xlabel('region')
_ = plt.ylabel('percent of vote for Obama')
plt.show()
# dataframe on the basis of east and west
east = df_all_state.loc[df_all_state["east_west"] == "east"]
west = df_all_state.loc[df_all_state["east_west"] == "west"]
dem_east_share = (east.dem_share.sum()/df_all_state.dem_share.sum())*100
dem_west_share = west.dem_share.sum()/df_all_state.dem_share.sum()*100

# creating the dataset 
data = {'East':dem_east_share, 
        'West':dem_west_share}

keys = list(data.keys()) 
values = list(data.values()) 

# Set default Seaborn style
sns.set()

# set the plot size
fig = plt.figure(figsize = (10, 5)) 

# creating the bar plot 
plt.bar(keys, values, color=['tab:blue', 'tab:blue'], width = 0.5) 
  
plt.xlabel("Democrates east_west Vote share Percentage") 
plt.ylabel("Votes")
plt.title("Percent Vote Counts") 
plt.show() 

# Vote Percent in 2008 election
print('Democrate east vote share {0:.2f}'.format(dem_east_share))
print('Democrate west vote share {0:.2f}'.format(dem_west_share))<jupyter_output><empty_output><jupyter_text>**Covariance** and the **Pearson correlation coefficient**<jupyter_code># Total swing votes
total_votes = df_all_state.total_votes

# Democrates Share
demcrats_share = df_all_state.dem_share

print('mean total votes {0:.2f}'.format((total_votes/1000).mean()))
print('mean percent for obama {0:.2f}'.format(demcrats_share.mean()))

# Set default Seaborn style
sns.set()

# figure size
plt.figure(figsize=(12, 7))

# vertical mean line 
plt.axvline((total_votes/1000).mean(), color='red',
            linestyle='dashed', linewidth=1,
            label='mean total votes')

# horizontal mean line
plt.axhline(demcrats_share.mean(), color='k',
            linestyle='dashed', linewidth=1,
            label='mean percent for obama')
# Plot
_ = plt.plot(total_votes/1000, demcrats_share, marker='.', linestyle='none')
_ = plt.xlabel('total votes (thousands)')
_ = plt.ylabel('percent of vote for Obama in all state')
_ = plt.legend()

plt.show()<jupyter_output>mean total votes 41.71
mean percent for obama 42.21<jupyter_text>__Linear regression by least squares__ __Residuals:__ Vertical distance between the data point and the line is called Residuals.


    


The residual has a negative value because the data point lies below the line. Each data point has a residual associated with it. __Least squares:__

We define the line that is closest to the data to be the line for which the sum of the squares of all of the residuals is **minimal**. This ***process, finding the parameters for which the sum of the squares of the residuals is minimal***, is called "**least squares**". There are many algorithms to do this in practice.

There are many algorithms to do this in practice.
for Example Numpy function - `np.polyfit()`. which performs ***least squares analysis*** with ***polynomial functions***.

>**Polyfit function** that computes a least squares polynomial for a given set of data. Polyfit generates the coefficients of the polynomial, which can be used to model a curve to fit the data.

We can use it because a ***linear function*** is a ***first degree polynomial***. 

>The **first** two arguments to this function are the `x` and `y` data. 

>The **third** argument is the **degree of the polynomial** ***we wish to fit***; for linear functions. 

The function returns the **slope** and **intercept** of the best **fit line**. ***The slope tells us that we get about 4 more percent votes for Obama for every 100,000 additional voters in a county***.<jupyter_code># Swing states 
import numpy as np

slope, intercept = np.polyfit(df_swing.total_votes, df_swing.dem_share, 1)
print(slope)
print(intercept)
# All states
slope, intercept = np.polyfit(df_all_state.total_votes, df_all_state.dem_share, 1)
print(slope)
print(intercept)
# Total swing votes
total_votes = df_all_state.total_votes

# Democrates Share
demcrats_share = df_all_state.dem_share

# Set default Seaborn style
plt.style.use('ggplot')

# Plot the PDF and label axes
plt.figure(figsize=(12,7), facecolor='lightgrey')

# Plot
_ = plt.plot(total_votes/1000, demcrats_share, marker='.', linestyle='none')
_ = plt.xlabel('total votes (thousands)')
_ = plt.ylabel('percent of vote for Obama in all state')
_ = plt.legend()

# Perform a linear regression using np.polyfit(): a, b
a, b = np.polyfit(total_votes, demcrats_share, 1)

# Print the results to the screen
print('slope =', a )
print('intercept =', b)

# Make theoretical line to plot
x = np.array([0, 1000])
y = a * x + b

# Add regression line to your plot
_ = plt.plot(x, y)

# Draw the plot
plt.show()<jupyter_output>No handles with labels found to put in legend.<jupyter_text>**Democrates Votes state-wise share**<jupyter_code># display records only with states
AK = (df_all_state.loc[df_all_state['state'] == 'AK']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MN = (df_all_state.loc[df_all_state['state'] == 'MN']['dem_share'].sum()/df_all_state.dem_share.sum())*100
WA = (df_all_state.loc[df_all_state['state'] == 'WA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MT = (df_all_state.loc[df_all_state['state'] == 'MT']['dem_share'].sum()/df_all_state.dem_share.sum())*100
ID = (df_all_state.loc[df_all_state['state'] == 'ID']['dem_share'].sum()/df_all_state.dem_share.sum())*100
ND = (df_all_state.loc[df_all_state['state'] == 'ND']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MI = (df_all_state.loc[df_all_state['state'] == 'MI']['dem_share'].sum()/df_all_state.dem_share.sum())*100
ME = (df_all_state.loc[df_all_state['state'] == 'ME']['dem_share'].sum()/df_all_state.dem_share.sum())*100
WI = (df_all_state.loc[df_all_state['state'] == 'WI']['dem_share'].sum()/df_all_state.dem_share.sum())*100
OR = (df_all_state.loc[df_all_state['state'] == 'OR']['dem_share'].sum()/df_all_state.dem_share.sum())*100
SD = (df_all_state.loc[df_all_state['state'] == 'SD']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NH = (df_all_state.loc[df_all_state['state'] == 'NH']['dem_share'].sum()/df_all_state.dem_share.sum())*100
VT = (df_all_state.loc[df_all_state['state'] == 'VT']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NY = (df_all_state.loc[df_all_state['state'] == 'NY']['dem_share'].sum()/df_all_state.dem_share.sum())*100
WY = (df_all_state.loc[df_all_state['state'] == 'WY']['dem_share'].sum()/df_all_state.dem_share.sum())*100
IA = (df_all_state.loc[df_all_state['state'] == 'IA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NE = (df_all_state.loc[df_all_state['state'] == 'NE']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MA = (df_all_state.loc[df_all_state['state'] == 'MA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
IL = (df_all_state.loc[df_all_state['state'] == 'IL']['dem_share'].sum()/df_all_state.dem_share.sum())*100
PA = (df_all_state.loc[df_all_state['state'] == 'PA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
CT = (df_all_state.loc[df_all_state['state'] == 'CT']['dem_share'].sum()/df_all_state.dem_share.sum())*100
RI = (df_all_state.loc[df_all_state['state'] == 'RI']['dem_share'].sum()/df_all_state.dem_share.sum())*100
CA = (df_all_state.loc[df_all_state['state'] == 'CA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
UT = (df_all_state.loc[df_all_state['state'] == 'UT']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NV = (df_all_state.loc[df_all_state['state'] == 'NV']['dem_share'].sum()/df_all_state.dem_share.sum())*100
OH = (df_all_state.loc[df_all_state['state'] == 'OH']['dem_share'].sum()/df_all_state.dem_share.sum())*100
IN = (df_all_state.loc[df_all_state['state'] == 'IN']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NJ = (df_all_state.loc[df_all_state['state'] == 'NJ']['dem_share'].sum()/df_all_state.dem_share.sum())*100
CO = (df_all_state.loc[df_all_state['state'] == 'CO']['dem_share'].sum()/df_all_state.dem_share.sum())*100
WV = (df_all_state.loc[df_all_state['state'] == 'WV']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MO = (df_all_state.loc[df_all_state['state'] == 'MO']['dem_share'].sum()/df_all_state.dem_share.sum())*100
KS = (df_all_state.loc[df_all_state['state'] == 'KS']['dem_share'].sum()/df_all_state.dem_share.sum())*100
DE = (df_all_state.loc[df_all_state['state'] == 'DE']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MD = (df_all_state.loc[df_all_state['state'] == 'MD']['dem_share'].sum()/df_all_state.dem_share.sum())*100
VA = (df_all_state.loc[df_all_state['state'] == 'VA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
KY = (df_all_state.loc[df_all_state['state'] == 'KY']['dem_share'].sum()/df_all_state.dem_share.sum())*100
DC = (df_all_state.loc[df_all_state['state'] == 'DC']['dem_share'].sum()/df_all_state.dem_share.sum())*100
AZ = (df_all_state.loc[df_all_state['state'] == 'AZ']['dem_share'].sum()/df_all_state.dem_share.sum())*100
OK = (df_all_state.loc[df_all_state['state'] == 'OK']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NM = (df_all_state.loc[df_all_state['state'] == "NM"]['dem_share'].sum()/df_all_state.dem_share.sum())*100
TN = (df_all_state.loc[df_all_state['state'] == 'TN']['dem_share'].sum()/df_all_state.dem_share.sum())*100
NC = (df_all_state.loc[df_all_state['state'] == 'NC']['dem_share'].sum()/df_all_state.dem_share.sum())*100
TX = (df_all_state.loc[df_all_state['state'] == 'TX']['dem_share'].sum()/df_all_state.dem_share.sum())*100
AR = (df_all_state.loc[df_all_state['state'] == 'AR']['dem_share'].sum()/df_all_state.dem_share.sum())*100
SC = (df_all_state.loc[df_all_state['state'] == 'SC']['dem_share'].sum()/df_all_state.dem_share.sum())*100
AL = (df_all_state.loc[df_all_state['state'] == 'AL']['dem_share'].sum()/df_all_state.dem_share.sum())*100
GA = (df_all_state.loc[df_all_state['state'] == 'GA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
MS = (df_all_state.loc[df_all_state['state'] == 'MS']['dem_share'].sum()/df_all_state.dem_share.sum())*100
LA = (df_all_state.loc[df_all_state['state'] == 'LA']['dem_share'].sum()/df_all_state.dem_share.sum())*100
FL = (df_all_state.loc[df_all_state['state'] == 'FL']['dem_share'].sum()/df_all_state.dem_share.sum())*100
HI = (df_all_state.loc[df_all_state['state'] == 'HI']['dem_share'].sum()/df_all_state.dem_share.sum())*100


data = { 
    'Alabama': AL, 
    'Alaska': AK, 
    #'American Samoa': AS, 
    'Arizona': AZ, 
    'Arkansas': AR, 
    'California': CA, 
    'Colorado': CO, 
    'Connecticut': CT, 
    'Delaware': DE, 
    'District of Columbia': DC, 
    'Florida': FL, 
    'Georgia': GA, 
    #'Guam': GU, 
    'Hawaii': HI, 
    'Idaho': ID, 
    'Illinois': IL, 
    'Indiana': IN, 
    'Iowa': IA, 
    'Kansas': KS, 
    'Kentucky': KY, 
    'Louisiana': LA, 
    'Maine': ME, 
    'Maryland': MD, 
    'Massachusetts': MA, 
    'Michigan': MI, 
    'Minnesota': MN, 
    'Mississippi': MS, 
    'Missouri': MO, 
    'Montana': MT, 
    #'Nebraska': NE', 
    'Nevada': NV, 
    'New Hampshire': NH, 
    'New Jersey': NJ, 
    'New Mexico': NM, 
    'New York': NY, 
    'North Carolina': NC, 
    'North Dakota': ND, 
    #'Northern Mariana Islands': MP, 
    'Ohio': OH, 
    'Oklahoma': OK, 
    'Oregon': OR, 
    'Pennsylvania': PA, 
    #'Puerto Rico': PR, 
    'Rhode Island': RI, 
    'South Carolina': SC, 
    'South Dakota': SD, 
    'Tennessee': TN, 
    'Texas': TX, 
    'Utah': UT, 
    'Vermont': VT, 
    #'Virgin Islands': VI, 
    'Virginia': VA, 
    'Washington': WA, 
    'West Virginia': WV, 
    'Wisconsin': WI, 
    'Wyoming': WY 
} 

keys = list(data.keys()) 
values = list(data.values()) 

# Set default Seaborn style
plt.style.use('ggplot')

# set the plot size
fig = plt.figure(figsize = (25, 15), facecolor='lightgray') 

# color
color = ['tab:blue', 'tab:orange', 'tab:green',
         'tab:red', 'tab:purple', 'tab:brown',
         'tab:pink', 'tab:gray', 'tab:olive',
         'tab:cyan']

# creating the bar plot 
plt.bar(keys, sorted(values), color=color, width = 0.5)
  
plt.xlabel("States") 
plt.ylabel("Percentage vote count")
plt.title("Democraet State-wise Vote Percent")
plt.xticks(rotation = 90)
plt.show()
sum(values)
# set the plot size
fig = plt.figure(figsize = (25, 10), facecolor='lightgray')
sns.barplot(keys, sorted(values))
plt.xlabel("States") 
plt.ylabel("Percentage vote count")
plt.title("Democraet State-wise Vote Percent")
plt.xticks(rotation = 90)
plt.show()<jupyter_output>/usr/local/lib/python3.6/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
  FutureWarning
{'fraction_non_alphanumeric': 0.14633999155150565, 'fraction_numerical': 0.020970369923360085, 'mean_word_length': 4.642322097378277, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 72, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '77820', 'license': 'MIT', 'n_tokens_mistral': 12364, 'n_tokens_neox': 11467, 'n_words': 3023, 'path': '22_Statistical-Thinking-in-Python-[Part -1]/01_Graphical_EDA_US_ElectionData.ipynb', 'repo_name': 'mohd-faizy/DataScience-With-Python', 'size': '33150'}