<jupyter_start><jupyter_text>Observations and Insights  Dependencies and starter code<jupyter_code># Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats as st
import numpy as np
from scipy.stats import linregress

# Study data files
mouse_metadata = "data/Mouse_metadata.csv"
study_results = "data/Study_results.csv"

# Read the mouse data and the study results
mouse_metadata = pd.read_csv(mouse_metadata)
study_results = pd.read_csv(study_results)

mouse_metadata.head(5)
study_results.head(5)
# Combine the data into a single dataset

trial_data = pd.merge(mouse_metadata, study_results, on='Mouse ID')
trial_data.head(5)<jupyter_output><empty_output><jupyter_text>Summary statistics<jupyter_code># Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen

tumor_volume_mean = trial_data.groupby('Drug Regimen')['Tumor Volume (mm3)'].mean()
tumor_volume_median = trial_data.groupby('Drug Regimen')['Tumor Volume (mm3)'].median()
tumor_volume_std = trial_data.groupby('Drug Regimen')['Tumor Volume (mm3)'].std()
tumor_volume_sem = trial_data.groupby('Drug Regimen')['Tumor Volume (mm3)'].sem()

tumor_study_summary = pd.DataFrame({
    "Tumor Volume Mean" : tumor_volume_mean,
    "Tumor Volume Median" : tumor_volume_median,
    "Tumor Volume STD" : tumor_volume_std,
    "Tumor Volume SEM" : tumor_volume_sem})

tumor_study_summary<jupyter_output><empty_output><jupyter_text>Bar plots<jupyter_code># Generate a bar plot showing number of data points for each treatment regimen using pandas

treatment_count_trim = trial_data[["Mouse ID","Drug Regimen"]]
treatment_count_rename = treatment_count_trim.rename(columns={"Mouse ID":"Treatment Count"})
treatment_count_df = treatment_count_rename.groupby("Drug Regimen").count()

treatment_count_df
treatment_chart = treatment_count_df.plot(kind="bar", figsize=(10,7))

plt.title("Drug Regimen Treatment Totals")
treatment_chart.set_xlabel("Treatment Type")
treatment_chart.set_ylabel("Number of Treatments")

plt.show()
# Generate a bar plot showing number of data points for each treatment regimen using pyplot

x_axis = x_axis = np.arange(len(treatment_count_df))
tick_locations = [value for value in x_axis]
y_axis = treatment_count_df["Treatment Count"]

plt.figure(figsize=(10,7))
plt.bar(x_axis, y_axis, color='r', align='center')
plt.xticks(tick_locations, ["Capomulin", "Ceftamin", "Infubinol", "Ketapril", "Naftisol", "Placebo", "Propriva", "Ramicane", "Stelasyn", "Zoniferol"],rotation='vertical')

plt.title("Drug Regimen Treatment Totals")
plt.xlabel("Treatment Type")
plt.ylabel("Number of Treatments")

plt.show()<jupyter_output><empty_output><jupyter_text>Pie plots<jupyter_code># Generate a pie plot showing the distribution of female versus male mice using pandas

gender_count_trim = trial_data[["Mouse ID","Sex"]]
gender_count_index = gender_count_trim.set_index("Sex")
gender_count_rename = gender_count_index.rename(columns={"Mouse ID":"Treatment Count"})
gender_count_df = gender_count_rename.groupby("Sex").count()
gender_list = gender_count_df.keys()

gender_count_df
gender_count_chart = gender_count_df.plot(kind="pie", y=gender_list, title=("Treatment by Sex"))
gender_count_chart.set_ylabel("")

plt.show()

# Generate a pie plot showing the distribution of female versus male mice using pyplot

sex = list(gender_count_df.index.values)
count = gender_count_df['Treatment Count']
colors = ['yellowgreen','red']

plt.title("Treatment by Sex")
plt.pie(count, labels=sex, colors=colors, autopct="%1.1f%%")
plt.axis("equal")
plt.show()<jupyter_output><empty_output><jupyter_text>Quartiles, outliers and boxplots<jupyter_code>group_by_mouse_max = trial_data.groupby("Mouse ID").max()
group_by_mouse_max_index = group_by_mouse_max.reset_index()
mouse_max = group_by_mouse_max_index[["Mouse ID", "Timepoint"]]


merge_df = pd.merge(mouse_max, trial_data, on =["Mouse ID", "Timepoint"], how="left")

top_performers = merge_df.loc[(merge_df["Drug Regimen"] == "Capomulin") | 
                                      (merge_df["Drug Regimen"] == "Ramicane") |
                                      (merge_df["Drug Regimen"] == "Infubinol") |
                                      (merge_df["Drug Regimen"] == "Ceftamin")]

top_performers.head(10)
tumor_size = top_performers["Tumor Volume (mm3)"]

quartiles = round(tumor_size.quantile([.25,.5,.75]))
lowerq = round(quartiles[0.25])
upperq = round(quartiles[0.75])
iqr = round(upperq-lowerq)

print(f"The lower quartile of Tumor Size (mm3) is: {lowerq}")
print(f"The upper quartile of Tumor Size (mm3) is: {upperq}")
print(f"The interquartile range of Tumor Size (mm3) is: {iqr}")
print(f"The the median of Tumor Size (mm3) is: {quartiles[0.5]} ")

lower_bound = lowerq - (1.5*iqr)
upper_bound = upperq + (1.5*iqr)
print(f"Values below {lower_bound} could be outliers.")
print(f"Values above {upper_bound} could be outliers.")
# Generate a box plot of the final tumor volume of each mouse across four regimens of interest

plt.figure(figsize=(5,8))

capomulin = top_performers.loc[top_performers["Drug Regimen"] == "Capomulin"]["Tumor Volume (mm3)"]
ramicane = top_performers.loc[top_performers["Drug Regimen"] == "Ramicane"] ["Tumor Volume (mm3)"]
infubinol = top_performers.loc[top_performers["Drug Regimen"] == "Infubinol"]["Tumor Volume (mm3)"]
ceftamin = top_performers.loc[top_performers["Drug Regimen"] == "Ceftamin"]["Tumor Volume (mm3)"]

labels = ["Capomulin", "Ramicane", "Infubinol", "drugs"]

plt.boxplot([capomulin,ramicane,infubinol,ceftamin], labels=labels)

plt.title("Treatment Comparison")
plt.ylabel("Final Tumor Volume (mm3)")

plt.show()<jupyter_output><empty_output><jupyter_text>Line and scatter plots<jupyter_code># Generate a line plot of time point versus tumor volume for a mouse treated with Capomulin
line_plot_columns = trial_data[["Mouse ID", "Drug Regimen", "Timepoint","Tumor Volume (mm3)"]]
capomulin_only = line_plot_columns.loc[(line_plot_columns["Drug Regimen"]=="Capomulin") &
                                      (line_plot_columns["Mouse ID"]=="s185")]

line_graph_columns = capomulin_only[["Timepoint", "Tumor Volume (mm3)"]]
line_graph_index = line_graph_columns.set_index("Timepoint")


line_plot_graph = line_graph_index.plot.line(title="Capomulin Treatment of Mouse s185")

plt.xlabel("Timepoint")
plt.ylabel("Tumor Volume (mm3)")

plt.show()
# Generate a scatter plot of mouse weight versus average tumor volume for the Capomulin regimen

scatter_plot_columns = trial_data[["Mouse ID","Drug Regimen", "Weight (g)", "Tumor Volume (mm3)"]]
capomulin_reg_only = scatter_plot_columns.loc[line_plot_columns["Drug Regimen"]=="Capomulin",:]

scatter_plot_avg = capomulin_reg_only.groupby(['Mouse ID']).mean()
scatter_plot_avg.plot(kind="scatter", x='Weight (g)', y='Tumor Volume (mm3)')
# Calculate the correlation coefficient and linear regression model for mouse weight and average tumor volume for the Capomulin regimen

x_values = scatter_plot_avg["Weight (g)"]
y_values = scatter_plot_avg["Tumor Volume (mm3)"]

(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")

plt.xlabel('Weight (g)')
plt.ylabel('Tumor Volume')
plt.show()
corr_matrix_df = scatter_plot_avg[["Weight (g)","Tumor Volume (mm3)"]]
corr_matrix_df.columns = corr_matrix_df.columns.str.replace("[_]", " ")
corr_matrix_df.corr(method='pearson')<jupyter_output><empty_output>