[go: up one dir, main page]

0% found this document useful (0 votes)
18 views8 pages

Chart Final Class

The document contains code for generating different types of plots including bar charts, histograms, line plots, scatter plots, pie charts, heatmaps, and box plots using Python libraries like Matplotlib and Pandas. Code snippets are provided to generate each type of plot using sample data.

Uploaded by

nahin963
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

Chart Final Class

The document contains code for generating different types of plots including bar charts, histograms, line plots, scatter plots, pie charts, heatmaps, and box plots using Python libraries like Matplotlib and Pandas. Code snippets are provided to generate each type of plot using sample data.

Uploaded by

nahin963
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Bar Chart (Question 1)

product = {"Product A": 150, "Product B": 200, "Product C":80,


"Product D":120}

import numpy as np
import matplotlib.pyplot as plt
labels = []
numbers = []
total = 0
for key, value in product.items():
labels.append(key)
numbers.append(value)
total += value
index = np.arange(len(labels))
plt.figure(figsize=(7,4))
plt.bar(index,numbers)
plt.xticks(index, labels, fontsize=10, rotation=0)
plt.ylabel('product', fontsize=10)
plt.title("total sales: {}".format(total))
plt.show()
histrogram (Question 2)
import matplotlib.pyplot as plt

scores = [85,90,78, 92, 88,85, 78, 95, 84, 88, 90, 88,92, 85]

plt.hist(scores, bins=4, edgecolor="black")


plt.xlabel('values')
plt.ylabel('Frequently')
plt.title('Histrogram Example')
plt.show()
Line Plot (Question 3)
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("Music/alphabet_stock_data.csv")
start_date = pd.to_datetime('2023-4-1')
end_date = pd.to_datetime('2023-11-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df2 = df.loc[new_df]
plt.figure(figsize=(10,10))
df2.plot(x='Date', y=['Open', 'Close']);
plt.suptitle('Opening/Closing stock prices of Alphabet Inc.,\n 01-04-
2023 to 30-09-2023', fontsize=12, color='black')
plt.xlabel("Date",fontsize=12, color='black')
plt.ylabel("$ price", fontsize=12, color='black')
plt.show()

<Figure size 1000x1000 with 0 Axes>


Scatter Plot (Question 4)
import matplotlib.pyplot as plt

# height and weight data


height = [160, 170, 155, 175, 180, 165]
weight = [60, 70, 55, 80, 85, 62]

# plot a scatter plot


plt.scatter(weight, height)
# set axis lables
plt.xlabel("Weight (Kg)")
plt.ylabel("Height (cm)")
# set chart title
plt.title("Height v/s Weight")
plt.show()
Pie Chart (Question 5)
import matplotlib.pyplot as plt

# product sales for sizes Small, Medium, and Large


sales = [0.35, 0.25, 0.15, 0.25]
lables = ["Product A", "Product B", "Product C", "Product D"]
colors = ["wheat", "lavender", "lightblue", "red"]

# plot a pie chart


plt.pie(sales, labels=lables, autopct="%1.1f%%", colors=colors)
plt.title("Pie Chart Sales Proportion")
plt.show()
Heatmap from Correlation Matrix (Question 6)
# Required libraries
import seaborn as sns
import matplotlib.pyplot as plt

# Load the iris dataset into a Pandas dataframe


iris_data = sns.load_dataset('iris')

# Creating the correlation matrix of the iris dataset


iris_corr_matrix = iris_data.corr()
print(iris_corr_matrix)

# Create the heatmap using the `heatmap` function of Seaborn


sns.heatmap(iris_corr_matrix, cmap='coolwarm', annot=True)

# Display the heatmap using the `show` method of the `pyplot` module
from matplotlib.
plt.show()
sepal_length sepal_width petal_length petal_width
sepal_length 1.000000 -0.117570 0.871754 0.817941
sepal_width -0.117570 1.000000 -0.428440 -0.366126
petal_length 0.871754 -0.428440 1.000000 0.962865
petal_width 0.817941 -0.366126 0.962865 1.000000

C:\Users\mahabub gazi\AppData\Local\Temp\
ipykernel_4672\878384592.py:9: FutureWarning: The default value of
numeric_only in DataFrame.corr is deprecated. In a future version, it
will default to False. Select only valid columns or specify the value
of numeric_only to silence this warning.
iris_corr_matrix = iris_data.corr()

BOX plot (Question 7)


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
normal = np.random.normal(0, 1, 10000) # loc, scale, size
quartiles = pd.DataFrame(normal).quantile([0.25, 0.5, 0.75, 1])[0]
fig, axs = plt.subplots(nrows=2)
fig.set_size_inches(14, 8)
# Boxplot of Normal distribution
plot1 = sns.boxplot(normal, ax=axs[0])
plot1.set(xlim=(-4, 4))
# Normal distribution
plot2 = sns.histplot(normal, ax=axs[1])
plot2.set(xlim=(-4, 4))
# Median line
plt.axvline(np.median(normal), color='r', linestyle='dashed',
linewidth=2)
for i, q in enumerate(quartiles):
# Quartile i line
plt.axvline(q, color='g', linestyle='dotted', linewidth=2)

You might also like