Matplotlib--Table Demo

本文介绍使用Python的matplotlib库来创建一个堆叠条形图,并在图表底部添加了一个表格来展示数据。通过具体的数据集和详细的代码实现,展示了如何设置颜色、调整布局等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
import matplotlib.pyplot as plt


data = [[ 66386, 174296,  75131, 577908,  32015],
        [ 58230, 381139,  78045,  99308, 160454],
        [ 89135,  80552, 152558, 497981, 603535],
        [ 78415,  81858, 150656, 193263,  69638],
        [139361, 331509, 343164, 781380,  52269]]

columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]

values = np.arange(0, 2500, 500)
value_increment = 1000

# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)

index = np.arange(len(columns)) + 0.3
bar_width = 0.4

# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.zeros(len(columns))

# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
    plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
    y_offset = y_offset + data[row]
    cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()

# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='bottom')

# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)

plt.ylabel("Loss in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')

plt.show()

很多代码没看懂。

xlaber,ylaber:分别在x轴和y轴的标签名称
xticks,yticks:没搞清楚。
title:是标题

### 关于推荐系统使用 ml-1m 数据集的资料与实现方法 ml-1m 数据集是 MovieLens 提供的一个经典数据集,包含约 100 万条评分记录,适用于构建和测试推荐系统。以下是关于如何使用 ml-1m 数据集构建推荐系统的详细说明: #### 1. 数据集简介 ml-1m 数据集包含用户对电影的评分信息,适合用于协同过滤、矩阵分解等推荐算法的研究。数据集中包括以下文件: - `ratings.dat`:用户的评分记录。 - `movies.dat`:电影的基本信息。 - `users.dat`:用户的基本信息。 数据格式如下[^1]: ```plaintext UserID::MovieID::Rating::Timestamp ``` #### 2. 环境配置 为了确保开发环境的稳定性,建议使用 Python 3.7 或 3.8 版本,并通过 Anaconda 创建虚拟环境[^3]。以下为创建环境的步骤: ```bash # 创建虚拟环境 conda create -n recsys python=3.7 # 激活虚拟环境 conda activate recsys ``` 安装必要的依赖库: ```bash pip install pandas numpy scikit-learn tensorflow matplotlib ``` #### 3. 数据加载与预处理 使用 Pandas 加载 ml-1m 数据集并进行预处理: ```python import pandas as pd # 加载数据 columns = ['user_id', 'movie_id', 'rating', 'timestamp'] data = pd.read_csv('ml-1m/ratings.dat', sep='::', names=columns, engine='python') # 查看数据基本信息 print(data.head()) print(data.describe()) # 转换时间戳为日期格式 data['timestamp'] = pd.to_datetime(data['timestamp'], unit='s') ``` #### 4. 推荐算法实现 以下是一个基于矩阵分解的推荐系统实现示例: ```python from sklearn.model_selection import train_test_split from sklearn.metrics.pairwise import cosine_similarity import numpy as np # 划分训练集和测试集 train_data, test_data = train_test_split(data, test_size=0.2, random_state=42) # 构建用户-物品矩阵 user_item_matrix = train_data.pivot_table(index='user_id', columns='movie_id', values='rating') # 计算相似度矩阵 similarity_matrix = cosine_similarity(user_item_matrix.fillna(0)) # 预测函数 def predict(user_id, movie_id): user_ratings = user_item_matrix.loc[user_id].fillna(0) similar_users = similarity_matrix[user_id - 1] weighted_sum = np.dot(similar_users, user_item_matrix[movie_id].fillna(0)) normalization = np.sum(similar_users[user_item_matrix[movie_id].notnull()]) return weighted_sum / normalization if normalization > 0 else 0 # 测试预测 user_id = 1 movie_id = 1193 predicted_rating = predict(user_id, movie_id) print(f"Predicted rating for user {user_id} on movie {movie_id}: {predicted_rating}") ``` #### 5. 模型评估 使用均方根误差(RMSE)评估模型性能: ```python from sklearn.metrics import mean_squared_error # 计算预测值 test_matrix = test_data.pivot_table(index='user_id', columns='movie_id', values='rating') predictions = test_matrix.applymap(lambda x: predict(x.name[0], x.name[1]) if pd.notnull(x) else None) # 去除空值并计算 RMSE rmse = np.sqrt(mean_squared_error(test_matrix.stack(), predictions.stack())) print(f"RMSE: {rmse}") ``` #### 6. 运行项目 如果使用 Java 实现推荐系统,可以参考以下步骤运行项目[^2]: 1. 打开 `RecommendSystemApplication.java` 文件。 2. 右键选择“Run”以启动应用程序。 #### 7. 自定义数据集 如果需要扩展或替换数据集,可以参考已有数据集的格式自定义数据[^4]。确保新数据集包含用户、物品和评分三个关键字段。 #### 8. 测试与部署 在 Windows 或 Linux 系统中,可以通过命令行测试模型效果[^5]。例如: ```bash python demo.py --image_dir data/test_image --weights data/model/best.pt --out_dir runs/test-result ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值