I'm working on the famous housing prices data set, and I encountered a problem with my xlabel not showing. I figured out that this is caused by plotting a colorbar. I'd like to know how I can plot the colorbar and still have my xlabel.
Edit: The dataset can be loaded with the sklearn library:
from sklearn.datasets.california_housing import fetch_california_housing
housing = fetch_california_housing()
This is the code without the 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();
Scatter Plot with colorbar but without xlabel:
This is the code with the xlabel (but no colorbar):
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();
Scatter Plot without colorbar but with xlabel:
Any tips or hints are greatly appreciated.
You need to define the matplotlib axes object in your df.plot()
call, here is a minimal example:
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 !
Which give:
Instead of: