Along with Company, Cluster, show the Mean return and volatility for each company as…
- User
Along with Company, Cluster, show the Mean return and volatility for each company as well.
centroids = k_means.cluster_centers_ fig = plt.figure(figsize=(16,10)) ax = fig.add_subplot(111) scatter = ax.scatter(X.iloc[:,0],X.iloc[:,1], c = k_means.labels_, cmap ="rainbow", label = X.index) ax.set_title('k-Means') ax.set_xlabel('Mean Return') ax.set_ylabel('Volatility') plt.colorbar(scatter)
zip joins x and y coordinates in pairs
for x,y,name in zip(X.iloc[:,0],X.iloc[:,1],X.index):
label = name plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='center') # horizontal alignment can be left, right or centerplt.plot(centroids[:,0],centroids[:,1],'sg',markersize=11)
cluster_label = pd.concat([pd.DataFrame(X.index), pd.DataFrame(k_means.labels_)],axis = 1) cluster_label.columns =['Company','Cluster'] cluster_label.sort_values(by=['Cluster'])
- Assistant
To display the mean return and volatility for each company along with the cluster information, you can create a new DataFrame that includes this information and then use it to create the scatter plot. Here's an example:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.cluster import KMeans # Generate sample data np.random.seed(0) X, y = make_blobs(n_samples=100, centers=3, random_state=0, cluster_std=0.5) # Perform k-means clustering k_means = KMeans(n_clusters=3).fit(X) # Calculate mean return and volatility for each company mean_return = X[:,0] volatility = X[:,1] company_info = pd.concat([pd.DataFrame(mean_return), pd.DataFrame(volatility)], axis=1) company_info.index = X.index # Create scatter plot with company information fig, ax = plt.subplots(figsize=(16, 10)) scatter = ax.scatter(mean_return, volatility, c=k_means.labels_, cmap="rainbow", label=X.index) ax.set_title('k-Means') ax.set_xlabel('Mean Return') ax.set_ylabel('Volatility') plt.colorbar(scatter) # Add labels for each company for x, y, name in zip(mean_return, volatility, X.index): label = name ax.annotate(label, (x, y), textcoords="offset points", xytext=(0, 10), ha='center') # Plot centroids centroids = k_means.cluster_centers_ ax.plot(centroids[:, 0], centroids[:, 1], 'sg', markersize=11) # Add cluster information to DataFrame cluster_label = pd.concat([pd.DataFrame(X.index), pd.DataFrame(k_means.labels_)], axis=1) cluster_label.columns = ['Company', 'Cluster']
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.