Skip to content

Commit 7fdaae6

Browse files
committed
moved polar plotting to python_toolkit.
1 parent 0ba5399 commit 7fdaae6

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

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

1877+
#deprecation warnings
1878+
if kwargs.pop("other_data", None) is not None:
1879+
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.")
1880+
1881+
if kwargs.pop("other_bins", None) is not None:
1882+
CONSOLE_LOGGER.warning("'other_bins' has been renamed. Please use 'value_bins' in future instead.")
1883+
value_bins = kwargs["other_bins"]
1884+
18781885
if ax is None:
18791886
_, ax = plt.subplots(subplot_kw={"projection": "polar"})
18801887

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

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

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

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

19761901
return ax
19771902

0 commit comments

Comments
 (0)