python-3.x - 散点图 matplotlib 结果相同的颜色
问题描述
我正在尝试从熊猫数据框中构建一个简单的散点图,但它会生成颜色完全相同的散点图。我检查了它是否适用于随机熊猫数据框。
这是一个 MWE。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cbook
import matplotlib as mpl
import matplotlib.cm as cm
#This dataframe works perfectly well.
df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('CRD'))
#Here is a dataframe converted to list, that doesn't work.
df['C'] = [4.0, 4.0, 4.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0]
df['D'] = [1.2, 1.6, 2.0, 1.2, 1.6, 1.6, 1.6, 1.6, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
df['R'] = [100.0, 100.0, 100.0, 100.0, 100.0, 1400.0, 1800.0, 2200.0, 100.0, 1400.0, 1800.0, 2200.0, 1000.0, 1500.0, 1700.0, 1900.0, 2200.0, 2500.0, 2800.0]
#My first hunch was that the column 'D' is a string but the dtypes returns it as a float64.. what am I missing?
#C float64
#D float64
#R float64
fig = plt.figure()
ax1 = plt.subplot(1,1,1)
im = ax1.scatter(df['C'], df['R'] , c=df['D'])
cb = fig.colorbar(im, ax=ax1)
cb.set_label('D')
ax1.set_ylabel('R')
ax1.set_xlabel('C')
fig.tight_layout()
plt.show()
plt.close()
解决方案
您的散点相互覆盖,因为大多数(df['C'],df['R'])
对是多重定义的。
print(df.groupby(['C','R','D']).apply(list))
产量
C R D
4.0 100.0 1.2 [C, R, D]
1.6 [C, R, D]
2.0 [C, R, D]
8.0 100.0 1.2 [C, R, D]
1.6 [C, R, D]
2.0 [C, R, D]
1400.0 1.6 [C, R, D]
2.0 [C, R, D]
1800.0 1.6 [C, R, D]
2.0 [C, R, D]
2200.0 1.6 [C, R, D]
2.0 [C, R, D]
16.0 1000.0 2.0 [C, R, D]
1500.0 2.0 [C, R, D]
1700.0 2.0 [C, R, D]
1900.0 2.0 [C, R, D]
2200.0 2.0 [C, R, D]
2500.0 2.0 [C, R, D]
2800.0 2.0 [C, R, D]
推荐阅读
- python - Django 2.1:如何获取每个对象中的对象列表,其中包含具有指向它们的外键的对象
- linux - 上传/下载较大文件时,服务器不返回任何内容(无标题、无数据)
- c# - .NET 列表
.Sort 使用 introsort,为什么最坏的情况是 O(n^2)? - mysql - MySQL 和 Laravel - 在之前和之后检查现有记录
- angular - Angular中canactivate方法中的API调用
- php - 如何清理查询以接受表名作为参数 PDO php
- angular6 - 无法使用 HttpTestController 在 Jasmine 和 Karma 中模拟 HttpClient
- ios - 当我尝试编辑文本时,searchBar.rx.textDidBeginEditing 不起作用
- c# - 如何使从水平滚动视图视图中滚动出来的项目淡出?[Xamarin 形式]
- java - 运行任何新的 android 项目的问题 - 未找到默认活动/无效的 Java 包