【发布时间】:2019-11-03 22:17:19
【问题描述】:
目前,我正在撰写一篇关于数据操作等的介绍性论文;但是...我正在处理的 CSV 有一些我希望在其上做散点图的事情!
我想要一个散点图来显示某些商品的销售量以及它们的平均价格,根据它们的区域区分所有数据(通过我假设的颜色)。
或者如果有办法使这成为可能... 这是我第一次使用 Python,我经常感到困惑
【问题讨论】:
标签: python pandas matplotlib scatter-plot
目前,我正在撰写一篇关于数据操作等的介绍性论文;但是...我正在处理的 CSV 有一些我希望在其上做散点图的事情!
我想要一个散点图来显示某些商品的销售量以及它们的平均价格,根据它们的区域区分所有数据(通过我假设的颜色)。
或者如果有办法使这成为可能... 这是我第一次使用 Python,我经常感到困惑
【问题讨论】:
标签: python pandas matplotlib scatter-plot
我不确定这是否是您的意思,但这里有一些工作代码,假设您有[(country, volume, price), ...] 格式的数据。如果没有,您可以根据需要将输入更改为scatter 方法。
import random
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
n_countries = 50
# get the data into "countries", for example
countries = ...
# in this example: countries is [('BS', 21, 25), ('WZ', 98, 25), ...]
df = pd.DataFrame(countries)
# arbitrary method to get a color
def get_color(i, max_i):
cmap = matplotlib.cm.get_cmap('Spectral')
return cmap(i/max_i)
# get the figure and axis - make a larger figure to fit more points
# add labels for metric names
def get_fig_ax():
fig = plt.figure(figsize=(14,14))
ax = fig.add_subplot(1, 1, 1)
ax.set_xlabel('volume')
ax.set_ylabel('price')
return fig, ax
# switch around the assignments depending on your data
def get_x_y_labels():
x = df[1]
y = df[2]
labels = df[0]
return x, y, labels
offset = 1 # offset just so annotations aren't on top of points
x, y, labels = get_x_y_labels()
fig, ax = get_fig_ax()
# add a point and annotation for each of the labels/regions
for i, region in enumerate(labels):
ax.annotate(region, (x[i] + offset, y[i] + offset))
# note that you must use "label" for "legend" to work
ax.scatter(x[i], y[i], color=get_color(i, len(x)), label=region)
# Add the legend just outside of the plot.
# The .1, 0 at the end will put it outside
ax.legend(loc='upper right', bbox_to_anchor=(1, 1, .1, 0))
plt.show()
【讨论】: