简体   繁体   English

带有颜色栏和日期时间轴刻度的散点图

[英]Scatter plot with colorbar and datetime axis ticks

I am getting lost in different methods used in matplotlib. 我迷失在matplotlib中使用的不同方法中。

I want to create a colour-coded scatter plot with a colorbar on the side and datetime on the x axis. 我想创建一个颜色编码的散点图,在侧面带有一个色条,在x轴上带有日期时间。

But depending on how I define my ax , I get different errors. 但是根据我定义ax ,我会得到不同的错误。 Below is the core of my code: 以下是我的代码的核心:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
import matplotlib.dates as mdates

#.....loading files etc.

norm = mcolors.Normalize(vmin=0,vmax=1000)
timerange = pd.date_range(start='2015-01-01', end='2016-01-01', freq='30D')

### PLOTTING 
fig = plt.figure(figsize=(6.,5))
ax = fig.add_subplot(111)

for Af in Afiles:
    for index, row in Af.iterrows():
        time = pd.to_datetime(row['date'], format="%Y-%m-%d")
        plt.scatter(time, row['A'], c=row['z'], norm=norm, cmap=colormap,edgecolor='k', lw=0.8, s=80)

plt.xticks(timerange, rotation=90)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%Y"))
plt.xlabel('Time', fontsize=11, color='k')

clb = fig.colorbar(ax)       
clb.ax.set_title('Value', y=-0.125, fontsize=11)
clb.ax.invert_yaxis()

fig.tight_layout()

this produces AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None' 这会产生AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'

but if I specify my ax as the scatter plot so that I can get my colour-coding working, I then have trouble with the axis formatter. 但是,如果我将ax指定为散点图,以便可以进行颜色编码,那么轴格式化程序就会遇到麻烦。 Writing instead ax = plt.scatter generates AttributeError: 'PathCollection' object has no attribute 'xaxis' . 相反,编写ax = plt.scatter产生AttributeError: 'PathCollection' object has no attribute 'xaxis'

How can I have both the colorbar AND formatted axis ticks? 如何同时获得颜色栏和格式化的轴刻度?

Don't call the scatter ax . 不要叫分散ax (This overwrites the existinge axes ax .) (这将覆盖现有的轴ax 。)
The colorbar expects as first argument a ScalarMappable (as eg the scatter). 彩条期望将ScalarMappable(例如散点图)作为第一个参数。 Since the scatters are all normalized, you can use it from the loop, 由于分散均已标准化,因此您可以从循环中使用它,

norm = plt.Normalize(...)
for bla in blubb:
    scatter = plt.scatter(..., norm=norm) 

Then, 然后,

clb = fig.colorbar(scatter)

The rest should stay the same. 其余应保持不变。

The basic idea is that you need to add an extra axis for the colorbar. 基本思想是您需要为色条添加一个额外的轴。

It's hard to know if this is an exact match, as you haven't provided a working example with data. 很难知道这是否完全匹配,因为您还没有提供一个有效的数据示例。 But this may at least serve as a template. 但这至少可以用作模板。

First, some example data: 首先,一些示例数据:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
import matplotlib.dates as mdates
from mpl_toolkits.axes_grid1 import make_axes_locatable

vmin = 0
vmax = 1000
timerange = pd.date_range(start='2015-01-01', end='2016-01-01', freq='30D')
N = len(timerange)

data = np.random.randint(vmin, vmax, size=N)
# z contains the colorbar values for each point
cmap = plt.get_cmap('Reds')
z = [cmap((x-vmin)/(vmax-vmin))[:3] for x in data]
df = pd.DataFrame({"value":data, "datetime":timerange, "z":z})

Now plot: 现在绘制:

fig = plt.figure(figsize=(6.,5))
ax = fig.add_subplot(111)

plt.scatter(x=df.datetime.values, y=df.value.values, c=df.z)

ax.set_xticklabels(timerange, rotation=90)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%Y"))
ax.set_xlabel('Time')

Now add colorbar: 现在添加颜色条:

norm = mcolors.Normalize(vmin=vmin,vmax=vmax)
m = cm.ScalarMappable(cmap='Reds', norm=norm)
m.set_array([(x-vmin)/(vmax-vmin) for x in df.value.values])

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
clb = plt.colorbar(m, cax=cax)   

散点图和颜色图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM