如何使用mysql表中的信息创建条形图?

n1bvdmb6  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(281)

如何使用数据库表(mysql)中的信息创建绘图?所以对于x轴,我想用 id 列和y轴我想使用 items in cart(number) . 你可以使用任何你想要的库,如果它能给出我想要的结果。现在在我的绘图(我附上照片)上的x标签,它给出了一个间隔500(05001000等),但我想有ID(1,2,3,4,…3024)和y标签,我想看到在购物车的项目。我附上了密码。我将感谢任何帮助。

import pymysql
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

conn = pymysql.connect(host='localhost', user='root', passwd='', db='amazon_cart')

cur = conn.cursor()
x = cur.execute("SELECT `id`,`items in cart(number)`,`product title` FROM `csv_9_05`")

plt.xlabel('Product Id')
plt.ylabel('Items in cart(number)')

rows = cur.fetchall()
df = pd.DataFrame([[xy for xy in x] for x in rows])

x=df[0]
y=df[1]

plt.bar(x,y)

plt.show()

cur.close()
conn.close()

表的sql

DROP TABLE IF EXISTS `csv_9_05`;
CREATE TABLE IF NOT EXISTS `csv_9_05` (
  `id` int(50) NOT NULL AUTO_INCREMENT,
  `product title` varchar(2040) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `product price` varchar(55) NOT NULL,
  `items in cart` varchar(2020) DEFAULT NULL,
  `items in cart(number)` varchar(50) DEFAULT NULL,
  `link` varchar(2024) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3025 DEFAULT CHARSET=latin1;
kxeu7u2r

kxeu7u2r1#

嗯。。。我认为重组你的数据库会让很多事情对你来说更容易。考虑到您在这里提供的模式,我建议您增加表的数量并进行一些连接。此外,整数值(购物车中的项目数)的数据类型应为 int ,不是 varchar . 您的表字段的名称中不应该有空格,而且我不知道为什么产品 id 一年中产品的数量 cart 是一对一的关系。
但这是另一个问题。仅仅重建这个数据库可能比你所要求的具体任务要复杂得多。你真的应该重新格式化你的数据库,如果你有什么问题,请告诉我。但现在我将根据您当前的配置来回答您的问题。
我对Pandas不是很精通,所以我将不用那个模块来回答这个问题。
如果您这样声明游标:

cursor = conn.cursor(pymysql.cursors.DictCursor)
x = cur.execute("SELECT `id`,`items in cart(number)`,`product title` FROM `csv_9_05`")

然后您的行将作为3024个字典的列表返回,即:

rows = cursor.fetchall()

# this will produce the following list:

# rows = [

# {'id': 1, 'items in cart(number)': 12, 'product_title': 'hammer'},

# {'id': 2, 'items in cart(number)': 5, 'product_title': 'nails'},

# {...},

# {'id': 3024, 'items in cart(number)': 31, 'product_title': 'watermelons'}

# ]

然后,策划变得非常容易。

plt.figure(1)
plt.bar([x['id'] for x in rows], [y['items in cart(number)'] for y in rows])
plt.xlabel('Product Id')
plt.ylabel('Items in cart(number)')
plt.show()
plt.close()

我认为应该这样做。

相关问题