Добавление количественных значений для дифференциации данных по цветам в легенде диаграммы рассеяния в Python? - PullRequest
0 голосов
/ 21 июня 2019

В настоящее время я работаю над вступительным документом по манипулированию данными и тому подобному;однако ... у CSV, над которым я работаю, есть кое-что, что я хотел бы сделать на графике разброса!

Я хочу, чтобы график разброса показал мне объем продаж по определенным предметам, а также их среднюю цену,дифференцировать все данные в соответствии с их регионом (я полагаю, через цвета).

Итак, я хочу узнать, могу ли я добавить столбец региона в качестве количественного значения enter image description here

или если есть способ сделать это возможным ... Я впервые использую Python, и я слишком часто путаюсь

1 Ответ

0 голосов
/ 21 июня 2019

Я не уверен, что это то, что вы имеете в виду, но вот некоторый рабочий код, предполагая, что у вас есть данные в формате [(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()

scatter plot with 50 points

...