DurhamTrees / durham_trees_analysis.py
Ziyuan111's picture
Update durham_trees_analysis.py
64aaee2 verified
raw
history blame
2.38 kB
# -*- coding: utf-8 -*-
"""durham_trees_analysis
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1OjlRC7F_UICGJM59jzSoy1o2crZxqXCl
"""
# Save this code as a file named 'durham_trees_analysis.py'
# Import display function and Image class
from IPython.display import display, Image
# Install required packages
import subprocess
import seaborn as sns
import matplotlib.pyplot as plt
# Install datasets package
subprocess.run(["pip", "install", "datasets", "geopandas", "seaborn", "matplotlib", "mplcursors", "pandas"])
# Import libraries
from datasets import load_dataset
import seaborn as sns
import matplotlib.pyplot as plt
import mplcursors
import pandas as pd
import geopandas as gpd
# Load dataset
dataset = load_dataset("Ziyuan111/DurhamTrees")
# Convert dataset to pandas DataFrame
df = pd.DataFrame(dataset['train'])
# Interactive scatter plot with seaborn and mplcursors
def plot_interactive_scatter():
scatter = sns.scatterplot(data=df, x='X', y='Y', hue='species')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend([],[], frameon=False)
cursor = mplcursors.cursor(hover=True)
@cursor.connect("add")
def on_add(sel):
sel.annotation.set_text(df.iloc[sel.target.index]['species'])
plt.savefig('interactive_scatter.png')
plt.show()
display(Image('interactive_scatter.png'))
# Plot tree planting sites with geopandas
def plot_tree_sites():
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.X, df.Y))
durham_center = {'x': -78.898619, 'y': 35.994033} # Durham, NC coordinates
fig, ax = plt.subplots(figsize=(10, 10))
gdf.plot(ax=ax, color='green')
buffer = 0.05
ax.set_xlim([durham_center['x'] - buffer, durham_center['x'] + buffer])
ax.set_ylim([durham_center['y'] - buffer, durham_center['y'] + buffer])
ax.set_title('Tree Planting Sites in Durham')
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_axis_off()
plt.savefig('tree_sites.png')
plt.show()
display(Image('tree_sites.png'))
# Print correlation matrix
def print_correlation_matrix():
correlation_matrix = df[['vocs', 'coremoved_ozperyr', 'coremoved_dolperyr']].corr()
print(correlation_matrix)
# Call the functions
plot_interactive_scatter()
plot_tree_sites()
print_correlation_matrix()
# Show the plot
plt.show()