Skip to content

Commit 3a79b38

Browse files
committed
moved polar plotting to python_toolkit.
1 parent bb8ee21 commit 3a79b38

1 file changed

Lines changed: 23 additions & 98 deletions

File tree

  • LadybugTools_Engine/Python/src/ladybugtools_toolkit

LadybugTools_Engine/Python/src/ladybugtools_toolkit/wind.py

Lines changed: 23 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,10 @@
4141
analysis_period_to_datetimes,
4242
describe_analysis_period,
4343
)
44+
from .bhom.logging import CONSOLE_LOGGER
4445
from python_toolkit.plot.timeseries import timeseries
45-
from .plot.utilities import contrasting_color, format_polar_plot
46+
from python_toolkit.plot.polar import polar
47+
from .plot.utilities import contrasting_color
4648

4749
# pylint: enable=E0401
4850

@@ -1838,13 +1840,13 @@ def plot_windrose(
18381840
self,
18391841
ax: plt.Axes = None,
18401842
directions: int = 36,
1841-
other_data: list[float] = None,
1842-
other_bins: list[float] = None,
1843-
colors: list[str | tuple[float] | Colormap] = None,
1843+
value_bins: list[float] = BEAUFORT_CATEGORIES.bins,
1844+
colors: list[str | tuple[float] | Colormap] = BEAUFORT_CATEGORIES.cmap,
18441845
title: str = None,
18451846
legend: bool = True,
18461847
ylim: tuple[float] = None,
18471848
label: bool = False,
1849+
**kwargs,
18481850
) -> plt.Axes:
18491851
"""Create a wind rose showing wind speed and direction frequency.
18501852
@@ -1853,12 +1855,9 @@ def plot_windrose(
18531855
The axes to plot this chart on. Defaults to None.
18541856
directions (int, optional):
18551857
The number of directions to use. Defaults to 36.
1856-
other_data (list[float], optional):
1857-
A list of other data to bin by direction.
1858-
If None, then wind speed will be used.
1859-
other_bins (list[float]):
1860-
The other data bins to use for the histogram. These bins are right inclusive.
1861-
If other data is None, then the default Beaufort bins will be used,
1858+
value_bins (list[float], optional):
1859+
The bins to use for the wind speed values. These bins are right inclusive.
1860+
If unset, then the default BEAUFORT_CATEGORIES bins will be used.
18621861
otherwise 11 evenly spaced bins will be used.
18631862
colors: (str | tuple[float] | Colormap, optional):
18641863
A list of colors to use for the other bins. May also be a colormap.
@@ -1876,103 +1875,29 @@ def plot_windrose(
18761875
plt.Axes: The axes object.
18771876
"""
18781877

1878+
#deprecation warnings
1879+
if kwargs.pop("other_data", None) is not None:
1880+
CONSOLE_LOGGER.warning("'other_data' can no longer be used as an argument to plot custom polar plots with the Wind class. Please use the python_toolkit.plot.polar polar() method instead for this functionality.")
1881+
1882+
if kwargs.pop("other_bins", None) is not None:
1883+
CONSOLE_LOGGER.warning("'other_bins' has been renamed. Please use 'value_bins' in future instead.")
1884+
value_bins = kwargs["other_bins"]
1885+
18791886
if ax is None:
18801887
_, ax = plt.subplots(subplot_kw={"projection": "polar"})
18811888

1882-
# create grouped data for plotting
1883-
binned = self.histogram(
1884-
directions=directions,
1885-
other_data=other_data,
1886-
other_bins=other_bins,
1887-
density=True,
1888-
remove_calm=True,
1889-
)
1889+
df = pd.concat([self.ws, self.wd], axis=1)
1890+
1891+
df = df[self.ws >= 1e-10] #remove times where the wind speed is calm, as direction doesn't make sense in this context
18901892

18911893
# set colors
18921894
if colors is None:
1893-
if other_data is None:
1894-
colors = [
1895-
to_hex(BEAUFORT_CATEGORIES.cmap(i))
1896-
for i in np.linspace(0, 1, len(binned.columns))
1897-
]
1898-
else:
1899-
colors = [
1900-
to_hex(plt.get_cmap("viridis")(i))
1901-
for i in np.linspace(0, 1, len(binned.columns))
1902-
]
1903-
if isinstance(colors, str):
1904-
colors = plt.get_cmap(colors)
1905-
if isinstance(colors, Colormap):
1906-
colors = [to_hex(colors(i)) for i in np.linspace(0, 1, len(binned.columns))]
1907-
if isinstance(colors, list | tuple):
1908-
if len(colors) != len(binned.columns):
1909-
raise ValueError(
1910-
f"colors must be a list of length {len(binned.columns)}, or a colormap."
1911-
)
1912-
1913-
# HACK to ensure that bar ends are curved when using a polar plot.
1914-
fig = plt.figure()
1915-
rect = [0.1, 0.1, 0.8, 0.8]
1916-
hist_ax = plt.Axes(fig, rect)
1917-
hist_ax.bar(np.array([1]), np.array([1]))
1895+
colors = BEAUFORT_CATEGORIES.cmap
19181896

19191897
if title is None or title == "":
1920-
ax.set_title(textwrap.fill(f"{self.source}", 75))
1921-
else:
1922-
ax.set_title(title)
1923-
1924-
theta_width = np.deg2rad(360 / directions)
1925-
patches = []
1926-
color_list = []
1927-
x = theta_width / 2
1928-
for _, data_values in binned.iterrows():
1929-
y = 0
1930-
for n, val in enumerate(data_values.values):
1931-
patches.append(
1932-
Rectangle(
1933-
xy=(x, y),
1934-
width=theta_width,
1935-
height=val,
1936-
alpha=1,
1937-
)
1938-
)
1939-
color_list.append(colors[n])
1940-
y += val
1941-
if label:
1942-
ax.text(x, y, f"{y:0.1%}", ha="center", va="center", fontsize="x-small")
1943-
x += theta_width
1944-
local_cmap = ListedColormap(np.array(color_list).flatten())
1945-
pc = PatchCollection(patches, cmap=local_cmap)
1946-
pc.set_array(np.arange(len(color_list)))
1947-
ax.add_collection(pc)
1948-
1949-
# construct legend
1950-
if legend:
1951-
handles = [
1952-
mpatches.Patch(color=colors[n], label=f"{i} to {j}")
1953-
for n, (i, j) in enumerate(binned.columns.values)
1954-
]
1955-
_ = ax.legend(
1956-
handles=handles,
1957-
bbox_to_anchor=(1.1, 0.5),
1958-
loc="center left",
1959-
ncol=1,
1960-
borderaxespad=0,
1961-
frameon=False,
1962-
fontsize="small",
1963-
title=binned.columns.name,
1964-
title_fontsize="small",
1965-
)
1966-
1967-
# set y-axis limits
1968-
if ylim is None:
1969-
ylim = (0, max(binned.sum(axis=1)))
1970-
if len(ylim) != 2:
1971-
raise ValueError("ylim must be a tuple of length 2.")
1972-
ax.set_ylim(ylim)
1973-
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))
1898+
title = textwrap.fill(f"{self.source}", 75)
19741899

1975-
format_polar_plot(ax, yticklabels=True)
1900+
ax = polar(df, "Wind Speed (m/s)", "Wind Direction (degrees)", ax, directions, value_bins, colors, title, legend, ylim, label)
19761901

19771902
return ax
19781903

0 commit comments

Comments
 (0)