[英]Plotting two data variables from an xarray dataset using hvplot
I have an xarray Dataset in python. I would like to plot two dependent (data) variables against each other using the hvplot library.我在 python 中有一个 xarray 数据集。我想 plot 两个因(数据)变量使用 hvplot 库相互比较。 Here's a simple example dataset:这是一个简单的示例数据集:
import numpy as np
import xarray as xr
import hvplot.xarray
# Create the dataset
time = np.linspace(0,10)
x = time*2 + 1
y = time*3 - 1
ds = xr.Dataset()
ds.coords['time'] = time
ds['x'] = (['time'],x)
ds['y'] = (['time'],y)
# Output
<xarray.Dataset>
Dimensions: (time: 50)
Coordinates:
* time (time) float64 0.0 0.2041 0.4082 0.6122 ... 9.388 9.592 9.796 10.0
Data variables:
x (time) float64 1.0 1.408 1.816 2.224 ... 19.78 20.18 20.59 21.0
y (time) float64 -1.0 -0.3878 0.2245 0.8367 ... 27.78 28.39 29.0
It's easy to plot x or y against time just by plot x 或 y 对时间很容易
ds.x.hvplot()
However what I want is to plot x against y.但是我想要的是 plot x 对 y。 I would have expected this to work:我原以为这会起作用:
ds.hvplot(x='x',y='y')
but this only plots one point at a time, with a slider for the 'time' coordinate.但这一次只绘制一个点,“时间”坐标为 slider。 xarray has a plot function which does plot as expected using matplotlib. xarray 有一个 plot function,它按预期使用 matplotlib 执行 plot。
ds.plot.scatter(x='x',y='y')
Is there any way to reproduce this with hvplot?有没有办法用 hvplot 重现这个?
Another possibility:另一种可能:
ds.y.assign_coords(x=ds.x).hvplot.scatter(x="x", y="y")
Don't know too much about xarray, but the following 2 approaches both work, but honestly I hope someone else comes with a nicer solution:不太了解xarray,但以下两种方法都有效,但老实说,我希望其他人能提供更好的解决方案:
ds.reset_index(dims_or_levels='time').hvplot.scatter(x='x', y='y')
Or:或者:
ds.hvplot.scatter(x='x', y='y', color='blue').overlay()
Probably the simplest way to plot two data variables against each other is to convert the dataset into a pandas DataFrame. Then plot using hvplot plot 两个数据变量相互比较的最简单方法可能是将数据集转换为 pandas DataFrame。然后 plot 使用 hvplot
import hvplot.pandas # to add .hvplot to DataFrames
# Convert Dataset to DataFrame, then select x,y
ds.to_dataframe().hvplot(x='x',y='y')
If the dataset has other variables the plots can be grouped using the 'by' argument如果数据集有其他变量,则可以使用“by”参数对图进行分组
ds.to_dataframe().hvplot(x='x',y='y',by=another_variable)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.