【问题标题】:Matplotlib problem: why is a colorbar deleting my xlabel? And how can i avoid it?Matplotlib 问题:为什么颜色条会删除我的 xlabel?我该如何避免呢?
【发布时间】:2021-02-17 14:33:55
【问题描述】:

我正在研究著名的房价数据集,但遇到了一个问题 我的 xlabel 没有显示。我发现这是由绘制颜色条引起的。我想知道如何绘制颜色条并且仍然拥有我的 xlabel。

编辑:可以使用 sklearn 库加载数据集:

from sklearn.datasets.california_housing import fetch_california_housing
housing = fetch_california_housing()

这是没有 xlabel 的代码:

housing.plot(kind='scatter', x = 'longitude', y= 'latitude', alpha = 0.2, figsize=(9,6),
         s = housing['population']/100, cmap = plt.get_cmap('jet'), 
         label = 'population',
         c = housing['median_house_value'],
         colorbar=True, 
         title = 'Housing prices in relation to location and population density'
         );

plt.legend();

带颜色条但不带 xlabel 的散点图:

这是带有 xlabel(但没有颜色条)的代码:

housing.plot(kind='scatter', x = 'longitude', y= 'latitude', alpha = 0.2, figsize=(9,6),
         s = housing['population']/100, cmap = plt.get_cmap('jet'), 
         label = 'population',
         c = housing['median_house_value'],
         colorbar=False, 
         title = 'Housing prices in relation to location and population density'
         );

 plt.legend();

没有颜色条但带有 xlabel 的散点图:

非常感谢任何提示或提示。

【问题讨论】:

  • 没有xlabel,因为您从未定义过xlabel 参数。我错过了什么吗?
  • 什么是housing?请阅读minimal reproducible example 并提供从您的问题复制和粘贴所需的任何内容的最小示例,以便我们重现您的问题。
  • @obchardon 没有定义 xlabel 也没有定义 ylabel 猜测它是从 x 和 y 变量中提取的。感谢您的评论。
  • @Mr.T 添加了用于定义数据框的代码。感谢您抽出宝贵时间
  • @JohanC 谢谢。但“plt.tight_layout”没有解决问题

标签: python matplotlib label visualization colorbar


【解决方案1】:

您需要在 df.plot() 调用中定义 matplotlib 轴对象,这是一个最小示例:

import pandas as pd
import matplotlib.pyplot as plt

# Dummy data
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')

# Create a figure and get the axes object
fig, ax = plt.subplots()

# The plot
iris.plot(kind    = 'scatter',              # Random parameter 
          x       = 'sepal_width', 
          y       = 'petal_width',  
          alpha   = 0.2, 
          figsize = (9,6), 
          cmap    = plt.get_cmap('jet'),
          s       = iris['sepal_length']*10,
          c       = iris['sepal_length'],
          colorbar= True,
          ax      = ax);                    # Pass the axes object !

哪个给:

代替:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    相关资源
    最近更新 更多