-
Notifications
You must be signed in to change notification settings - Fork 111
/
plot.py
2386 lines (2034 loc) · 74.5 KB
/
plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import numbers
import warnings
from copy import deepcopy
import re
from bokeh.plotting import figure as _figure
import pandas as pd
import numpy as np
from bokeh.models import (
HoverTool,
ColumnDataSource,
DatetimeTickFormatter,
LinearColorMapper,
LogColorMapper,
CategoricalColorMapper,
ColorBar,
FuncTickFormatter,
WheelZoomTool,
)
from bokeh.models.tickers import FixedTicker
from bokeh.palettes import all_palettes, Inferno256
from bokeh.models.ranges import FactorRange
from bokeh.transform import dodge, cumsum
from bokeh.core.properties import value as _value
from bokeh.models.glyphs import Text
from bokeh.models.callbacks import CustomJS
from bokeh.events import Tap
from pandas.core.base import PandasObject
from .base import show, embedded_html
from .geoplot import geoplot
def check_type(data):
"""Checks type of provided data array."""
if isinstance(data[0], numbers.Number):
return "numeric"
elif isinstance(data[0], (np.datetime64, datetime.datetime, datetime.date)):
return "datetime"
else:
return "object"
def get_colormap(colormap, N_cols):
"""Returns a colormap with <N_cols> colors. <colormap> can be either None,
a string with the name of a Bokeh color palette or a list/tuple of colors."""
if colormap is None:
if N_cols <= 10:
colormap = all_palettes["Category10"][10][:N_cols]
elif N_cols <= 20:
colormap = all_palettes["Category20"][N_cols]
else:
colormap = all_palettes["Category20"][20] * int(N_cols / 20 + 1)
colormap = colormap[:N_cols]
elif isinstance(colormap, str):
if colormap in all_palettes:
colormap = all_palettes[colormap]
max_key = max(colormap.keys())
if N_cols <= max_key:
colormap = colormap[N_cols]
else:
colormap = colormap[max_key]
colormap = colormap * int(N_cols / len(colormap) + 1)
colormap = colormap[:N_cols]
else:
raise ValueError(
"Could not find <colormap> with name %s. The following predefined colormaps are supported (see also https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ): %s"
% (colormap, list(all_palettes.keys()))
)
elif isinstance(colormap, (list, tuple)):
colormap = colormap * int(N_cols / len(colormap) + 1)
colormap = colormap[:N_cols]
else:
raise ValueError(
"<colormap> can onyl be None, a name of a colorpalette as string( see https://bokeh.pydata.org/en/latest/docs/reference/palettes.html ) or a list/tuple of colors."
)
return colormap
def _times_to_string(times):
types = []
for t in times:
t = pd.to_datetime(t)
if t.microsecond > 0:
types.append("microsecond")
elif t.second > 0:
types.append("second")
elif t.hour > 0:
types.append("hour")
else:
types.append("date")
if "microsecond" in types:
return [pd.to_datetime(t).strftime("%Y/%m/%d %H:%M:%S.%f") for t in times]
elif "second" in types:
return [pd.to_datetime(t).strftime("%Y/%m/%d %H:%M:%S") for t in times]
elif "hour" in types:
return [pd.to_datetime(t).strftime("%Y/%m/%d %H:%M") for t in times]
elif "date" in types:
return [pd.to_datetime(t).strftime("%Y/%m/%d") for t in times]
def plot(
df_in,
figure=None,
x=None,
y=None,
kind="line",
figsize=None,
use_index=True,
title="",
legend="top_right",
logx=False,
logy=False,
xlabel=None,
ylabel=None,
xticks=None,
yticks=None,
xlim=None,
ylim=None,
fontsize=None, # TODO:
color=None,
colormap=None,
category=None,
histogram_type=None,
stacked=False,
weights=None,
bins=None,
normed=False,
cumulative=False,
show_average=False,
plot_data_points=False,
plot_data_points_size=5,
number_format=None,
disable_scientific_axes=None,
show_figure=True,
return_html=False,
panning=True,
zooming=True,
toolbar_location="right",
hovertool=True,
hovertool_string=None,
vertical_xlabel=False,
webgl=True,
**kwargs
):
"""Method for creating a interactive with 'Bokeh' as plotting backend. Available
plot kinds are:
* line
* point
* scatter
* bar / barh
* hist
* area
* pie
* map
Examples
--------
>>> df.plot_bokeh.line()
>>> df.plot_bokeh.scatter(x='x',y='y')
These plotting methods can also be accessed by calling the accessor as a
method with the ``kind`` argument (except of "map" plot):
``df.plot_bokeh(kind='line')`` is equivalent to ``df.plot_bokeh.line()``
For more information about the individual plot kind implementations, have a
look at the underlying method accessors (like df.plot_bokeh.line) or visit
https://github.com/PatrikHlobil/Pandas-Bokeh.
"""
# Make a local copy of the DataFrame:
df = df_in.copy()
if isinstance(df, pd.Series):
df = pd.DataFrame(df)
if kind == "map":
return mapplot(
df,
x=x,
y=y,
figsize=figsize,
title=title,
legend=legend,
xlabel=xlabel,
ylabel=ylabel,
xlim=xlim,
color=color,
colormap=colormap,
category=category,
show_figure=show_figure,
return_html=return_html,
panning=panning,
zooming=zooming,
toolbar_location=toolbar_location,
hovertool=hovertool,
hovertool_string=hovertool_string,
webgl=webgl,
**kwargs
)
# Get and check options for base figure:
figure_options = {
"title": title,
"toolbar_location": toolbar_location,
"active_scroll": "wheel_zoom",
"plot_width": 600,
"plot_height": 400,
"output_backend": "webgl",
}
if not figsize is None:
width, height = figsize
figure_options["plot_width"] = width
figure_options["plot_height"] = height
if logx:
figure_options["x_axis_type"] = "log"
if logy:
figure_options["y_axis_type"] = "log"
if not xlabel is None:
figure_options["x_axis_label"] = xlabel
if not ylabel is None:
figure_options["y_axis_label"] = ylabel
if not xlim is None:
if not isinstance(xlim, (tuple, list)):
raise ValueError("<xlim> must be a list/tuple of form (x_min, x_max).")
elif len(xlim) != 2:
raise ValueError("<xlim> must be a list/tuple of form (x_min, x_max).")
else:
figure_options["x_range"] = xlim
if not ylim is None:
if not isinstance(ylim, (tuple, list)):
raise ValueError("<ylim> must be a list/tuple of form (y_min, y_max).")
elif len(ylim) != 2:
raise ValueError("<ylim> must be a list/tuple of form (y_min, y_max).")
else:
figure_options["y_range"] = ylim
if webgl:
figure_options["output_backend"] = "webgl"
if number_format is None:
number_format = ""
else:
number_format = "{%s}" % number_format
# Check plot kind input:
allowed_kinds = [
"line",
"step",
"point",
"scatter",
"bar",
"barh",
"hist",
"area",
"pie",
"map",
]
if kind not in allowed_kinds:
allowed_kinds = "', '".join(allowed_kinds)
raise ValueError("Allowed plot kinds are '%s'." % allowed_kinds)
# Check hovertool_string and define additional columns to keep in source:
additional_columns = []
if hovertool_string is not None:
if not isinstance(hovertool_string, str):
raise ValueError("<hovertool_string> can only be None or a string.")
# Search for hovertool_string columns in DataFrame:
for s in re.findall("@[^\s\{]+", hovertool_string):
s = s[1:]
if s in df.columns:
additional_columns.append(s)
for s in re.findall("@\{.+\}", hovertool_string):
s = s[2:-1]
if s in df.columns:
additional_columns.append(s)
# Set standard linewidth:
if "line_width" not in kwargs:
kwargs["line_width"] = 2
# Get x-axis Name and Values:
delete_in_y = None
if not x is None:
if issubclass(x.__class__, pd.Index) or issubclass(x.__class__, pd.Series):
if x.name is not None:
name = str(x.name)
else:
name = ""
x = x.values
elif x in df.columns:
delete_in_y = x
name = str(x)
x = df[x].values
elif isinstance(x, (tuple, list, type(np.array))):
if len(x) == len(df):
x = x
name = ""
else:
raise Exception(
"Length of provided <x> argument does not fit length of DataFrame or Series."
)
else:
raise Exception(
"Please provide for the <x> parameter either a column name of the DataFrame/Series or an array of the same length."
)
else:
if use_index:
x = df.index.values
if not df.index.name is None:
name = str(df.index.name)
else:
name = ""
else:
x = np.linspace(0, len(df) - 1, len(df))
name = ""
# Define name of axis of x-values (for horizontal plots like barh, this corresponds
# to y-axis):
if kind == "barh":
if "y_axis_label" not in figure_options:
figure_options["y_axis_label"] = name
else:
if "x_axis_label" not in figure_options:
figure_options["x_axis_label"] = name
# Check type of x-axis:
if check_type(x) == "datetime":
figure_options["x_axis_type"] = "datetime"
xaxis_type = "datetime"
if not xlim is None:
starttime, endtime = xlim
try:
starttime = pd.to_datetime(starttime)
except:
raise ValueError("Could not parse x_min input of <xlim> as datetime.")
try:
endtime = pd.to_datetime(endtime)
except:
raise ValueError("Could not parse x_max input of <xlim> as datetime.")
figure_options["x_range"] = (starttime, endtime)
elif check_type(x) == "numeric":
xaxis_type = "numerical"
else:
xaxis_type = "categorical"
if kind in ["bar", "barh", "pie"]:
xaxis_type = "categorical"
x_old = x
x_labels_dict = None
if xaxis_type == "categorical":
if check_type(x) == "datetime":
x = _times_to_string(x)
else:
x = [str(el) for el in x]
if kind != "hist":
x_labels_dict = dict(zip(range(len(x)), x))
x = list(range(len(x)))
if "x_axis_type" in figure_options:
del figure_options["x_axis_type"]
# Determine data cols to plot (only plot numeric data):
if y is None:
cols = df.columns
elif not isinstance(y, (list, tuple)):
cols = [y]
else:
cols = y
data_cols = []
for i, col in enumerate(cols):
if col not in df.columns:
raise Exception(
"Could not find '%s' in the columns of the provided DataFrame/Series. Please provide for the <y> parameter either a column name of the DataFrame/Series or an array of the same length."
% col
)
if np.issubdtype(df[col].dtype, np.number):
data_cols.append(col)
if len(data_cols) == 0:
raise Exception("No numeric data columns found for plotting.")
# Convert y-column names into string representation:
df.rename(columns={col: str(col) for col in data_cols}, inplace=True)
data_cols = [str(col) for col in data_cols]
# Delete x column if it appears in y columns:
if not delete_in_y is None:
if delete_in_y in data_cols:
data_cols.remove(delete_in_y)
N_cols = len(data_cols)
if len(data_cols) == 0:
raise Exception(
"The only numeric column is the column %s that is already used on the x-axis."
% delete_in_y
)
# Autodetect y-label if no y-label is provided by user and only one y-column exists:
if N_cols == 1:
if kind == "barh":
if "x_axis_label" not in figure_options:
figure_options["x_axis_label"] = data_cols[0]
else:
if "y_axis_label" not in figure_options:
figure_options["y_axis_label"] = data_cols[0]
# Get Name of x-axis data:
if kind == "barh":
xlabelname = (
figure_options["y_axis_label"]
if figure_options.get("y_axis_label", "") != ""
else "x"
)
else:
xlabelname = (
figure_options["x_axis_label"]
if figure_options.get("x_axis_label", "") != ""
else "x"
)
# Create Figure for plotting:
p = _figure(**figure_options)
if "x_axis_type" not in figure_options:
figure_options["x_axis_type"] = None
# For categorical plots, set the xticks:
if x_labels_dict is not None:
p.xaxis.formatter = FuncTickFormatter(
code="""
var labels = %s;
return labels[tick];
"""
% x_labels_dict
)
# Use figure when passed by user:
if figure is not None:
p = figure
# Define ColumnDataSource for Plot if kind != "hist":
if kind != "hist":
source = {col: df[col].values for col in data_cols}
source["__x__values"] = x
source["__x__values_original"] = x_old
for kwarg, value in kwargs.items():
if value in df.columns:
source[value] = df[value].values
for add_col in additional_columns:
source[add_col] = df[add_col].values
# Define colormap
if kind not in ["scatter", "pie"]:
colormap = get_colormap(colormap, N_cols)
if not color is None:
colormap = get_colormap([color], N_cols)
# Add Glyphs to Plot:
if kind == "line":
p = lineplot(
p,
source,
data_cols,
colormap,
hovertool,
xlabelname,
figure_options["x_axis_type"],
plot_data_points,
plot_data_points_size,
hovertool_string,
number_format,
**kwargs
)
if kind == "step":
p = stepplot(
p,
source,
data_cols,
colormap,
hovertool,
xlabelname,
figure_options["x_axis_type"],
plot_data_points,
plot_data_points_size,
hovertool_string,
number_format,
**kwargs
)
if kind == "point":
p = pointplot(
p,
source,
data_cols,
colormap,
hovertool,
hovertool_string,
xlabelname,
figure_options["x_axis_type"],
number_format,
**kwargs
)
if kind == "scatter":
if N_cols > 2:
raise Exception(
"For scatterplots <x> and <y> values can only be a single column of the DataFrame, not a list of columns. Please specify both <x> and <y> columns for a scatterplot uniquely."
)
# Get and set y-labelname:
y_column = data_cols[0]
if "y_axis_label" not in figure_options:
p.yaxis.axis_label = y_column
# Get values for y-axis:
y = df[y_column].values
# Delete additionally created values by pandas.plotting:
for add_param in ["s", "c"]:
if add_param in kwargs:
del kwargs[add_param]
# Get values for categorical colormap:
category_values = None
if category in df.columns:
category_values = df[category].values
elif not category is None:
raise Exception(
"<category> parameter has to be either None or the name of a single column of the DataFrame"
)
scatterplot(
p,
df,
x,
x_old,
y,
category,
category_values,
colormap,
hovertool,
hovertool_string,
additional_columns,
x_axis_type=figure_options["x_axis_type"],
xlabelname=xlabelname,
ylabelname=y_column,
**kwargs
)
if kind == "bar" or kind == "barh":
# Define data source for barplot:
data = {col: df[col].values for col in data_cols}
data["__x__values"] = x
data["__x__values_original"] = x_old
source = ColumnDataSource(data)
for kwarg, value in kwargs.items():
if value in df.columns:
source.data[value] = df[value].values
for add_col in additional_columns:
source.data[add_col] = df[add_col].values
# Create Figure (just for categorical barplots):
del figure_options["x_axis_type"]
if "y_axis_label" not in figure_options and kind == "barh":
figure_options["y_axis_label"] = xlabelname
p = _figure(**figure_options)
figure_options["x_axis_type"] = None
if figure is not None:
p = figure
# Set xticks:
if kind == "bar":
p.xaxis.formatter = FuncTickFormatter(
code="""
var labels = %s;
return labels[tick];
"""
% x_labels_dict
)
elif kind == "barh":
p.yaxis.formatter = FuncTickFormatter(
code="""
var labels = %s;
return labels[tick];
"""
% x_labels_dict
)
if not stacked:
if N_cols >= 3:
base_width = 0.5
else:
base_width = 0.35
width = base_width / (N_cols - 0.5)
if N_cols == 1:
shifts = [0]
else:
delta_shift = base_width / (N_cols - 1)
shifts = [-base_width / 2 + i * delta_shift for i in range(N_cols)]
for i, name, color, shift in zip(
range(N_cols), data_cols, colormap, shifts
):
if kind == "bar":
glyph = p.vbar(
x=dodge("__x__values", shift, range=p.x_range),
top=name,
width=width,
source=source,
color=color,
legend=" " + name,
**kwargs
)
hovermode = "vline"
elif kind == "barh":
glyph = p.hbar(
y=dodge("__x__values", shift, range=p.y_range),
right=name,
height=width,
source=source,
color=color,
legend=" " + name,
**kwargs
)
hovermode = "hline"
if hovertool:
my_hover = HoverTool(mode=hovermode, renderers=[glyph])
if hovertool_string is None:
my_hover.tooltips = [
(xlabelname, "@__x__values_original"),
(name, "@{%s}" % name),
]
else:
my_hover.tooltips = hovertool_string
p.add_tools(my_hover)
if stacked:
legend_ref = [_value(col) for col in data_cols]
if kind == "bar":
glyph = p.vbar_stack(
data_cols,
x="__x__values",
width=0.8,
source=source,
color=colormap,
legend=legend_ref,
**kwargs
)
hovermode = "vline"
elif kind == "barh":
glyph = p.hbar_stack(
data_cols,
y="__x__values",
height=0.8,
source=source,
color=colormap,
legend=legend_ref,
**kwargs
)
hovermode = "hline"
if hovertool:
my_hover = HoverTool(mode=hovermode, renderers=[glyph[-1]])
if hovertool_string is None:
my_hover.tooltips = [(xlabelname, "@__x__values_original")] + [
(col, "@{%s}" % col) for col in data_cols
]
else:
my_hover.tooltips = hovertool_string
p.add_tools(my_hover)
if kind == "hist":
# Disable line_color (for borders of histogram bins) per default:
if not "line_color" in kwargs:
kwargs["line_color"] = None
elif kwargs["line_color"] == True:
del kwargs["line_color"]
if "by" in kwargs and y is None:
y = kwargs["by"]
del kwargs["by"]
# Check for stacked keyword:
if stacked and histogram_type not in [None, "stacked"]:
warnings.warn(
"<histogram_type> was set to '%s', but was overriden by <stacked>=True parameter."
% histogram_type
)
histogram_type = "stacked"
elif stacked and histogram_type is None:
histogram_type = "stacked"
# Set xlabel if only one y-column is given and user does not override this via
# xlabel parameter:
if len(data_cols) == 1 and xlabel is None:
p.xaxis.axis_label = data_cols[0]
# If Histogram should be plotted, calculate bins, aggregates and
# averages:
# Autocalculate bins if bins are not specified:
if bins is None:
values = df[data_cols].values
values = values[~np.isnan(values)]
data, bins = np.histogram(values)
# Calculate bins if number of bins is given:
elif isinstance(bins, int):
if bins < 1:
raise ValueError(
"<bins> can only be an integer>0, a list or a range of numbers."
)
values = df[data_cols].values
values = values[~np.isnan(values)]
v_min, v_max = values.min(), values.max()
bins = np.linspace(v_min, v_max, bins + 1)
bins = list(bins)
if not weights is None:
if weights not in df.columns:
raise ValueError(
"Columns '%s' for <weights> is not in provided DataFrame."
)
else:
weights = df[weights].values
aggregates = []
averages = []
for col in data_cols:
values = df[col].values
if not weights is None:
not_nan = ~(np.isnan(values) | np.isnan(weights))
values_not_nan = values[not_nan]
weights_not_nan = weights[not_nan]
if sum(not_nan) < len(not_nan):
warnings.warn(
"There are NaN values in column '%s' or in the <weights> column. For the histogram, these rows have been neglected."
% col,
Warning,
)
else:
not_nan = ~np.isnan(values)
values_not_nan = values[not_nan]
weights_not_nan = None
if sum(not_nan) < len(not_nan):
warnings.warn(
"There are NaN values in column '%s'. For the histogram, these rows have been neglected."
% col,
Warning,
)
average = np.average(values_not_nan, weights=weights_not_nan)
averages.append(average)
data, bins = np.histogram(
values_not_nan, bins=bins, weights=weights_not_nan
)
if normed:
data = data / np.sum(data) * normed
if cumulative:
data = np.cumsum(data)
aggregates.append(data)
p = histogram(
p,
df,
data_cols,
colormap,
aggregates,
bins,
averages,
hovertool,
hovertool_string,
additional_columns,
normed,
cumulative,
show_average,
histogram_type,
logy,
**kwargs
)
if kind == "area":
p = areaplot(
p,
source,
data_cols,
colormap,
hovertool,
hovertool_string,
xlabelname,
figure_options["x_axis_type"],
stacked,
normed,
**kwargs
)
if kind == "pie":
if figure is not None:
raise ValueError("<figure> keyword is not supported for pie-charts.")
source["__x__values"] = x_old
p = pieplot(
source,
data_cols,
colormap,
hovertool,
hovertool_string,
figure_options,
xlabelname,
**kwargs
)
# Set xticks:
if not xticks is None:
p.xaxis[0].ticker = list(xticks)
elif (xaxis_type == "numerical" and kind not in ["hist", "scatter"]) or (
x_labels_dict is not None and kind != "barh"
):
p.xaxis.ticker = x
elif kind == "barh":
p.yaxis.ticker = x
if not yticks is None:
p.yaxis.ticker = yticks
# Format datetime ticks correctly:
if figure_options["x_axis_type"] == "datetime":
p.xaxis.formatter = DatetimeTickFormatter(
milliseconds=["%H:%M:%S.%f"],
seconds=["%H:%M:%S"],
minutes=["%H:%M:%S"],
hours=["%H:%M:%S"],
days=["%d %B %Y"],
months=["%d %B %Y"],
years=["%d %B %Y"],
)
# Rotate xlabel if wanted:
if vertical_xlabel:
p.xaxis.major_label_orientation = np.pi / 2
# Set panning option:
if panning is False:
p.toolbar.active_drag = None
# Set zooming option:
if zooming is False:
p.toolbar.active_scroll = None
# Set click policy for legend:
if not stacked and kind != "pie":
p.legend.click_policy = "hide"
# Hide legend if wanted:
if not legend:
p.legend.visible = False
# Modify legend position:
else:
if legend is True:
p.legend.location = "top_right"
elif legend in [
"top_left",
"top_center",
"top_right",
"center_left",
"center",
"center_right",
"bottom_left",
"bottom_center",
"bottom_right",
]:
p.legend.location = legend
else:
raise ValueError(
"Legend can only be True/False or one of 'top_left', 'top_center', 'top_right', 'center_left', 'center', 'center_right', 'bottom_left', 'bottom_center', 'bottom_right'"
)
# Scientific formatting for axes:
if disable_scientific_axes is None:
pass
elif disable_scientific_axes == "x":
p.xaxis[0].formatter.use_scientific = False
elif disable_scientific_axes == "y":
p.yaxis[0].formatter.use_scientific = False
elif disable_scientific_axes in ["xy", True]:
p.xaxis[0].formatter.use_scientific = False
p.yaxis[0].formatter.use_scientific = False
else:
raise ValueError(
"""Keyword parameter <disable_scientific_axes> only accepts "xy", True, "x", "y" or None."""
)
# Display plot if wanted
if show_figure:
show(p)
# Return as (embeddable) HTML if wanted:
if return_html:
return embedded_html(p)
# Return plot:
return p
def _base_lineplot(
linetype,
p,
source,
data_cols,
colormap,
hovertool,
xlabelname,
x_axis_type,
plot_data_points,
plot_data_points_size,
hovertool_string,
number_format,
**kwargs
):
"""Adds lineplot to figure p for each data_col."""
if "marker" in kwargs:
marker = kwargs["marker"]
del kwargs["marker"]
else:
marker = "circle"
# Add line (and optional scatter glyphs) to figure:
linetype = getattr(p, linetype.lower())
for name, color in zip(data_cols, colormap):
glyph = linetype(
x="__x__values",
y=name,
legend=" " + name,
source=source,
color=color,
**kwargs
)
if plot_data_points:
p.scatter(
x="__x__values",
y=name,
legend=" " + name,
source=source,
color=color,
marker=marker,
size=plot_data_points_size,
)
if hovertool:
my_hover = HoverTool(mode="vline", renderers=[glyph])
if hovertool_string is None:
if x_axis_type == "datetime":
my_hover.tooltips = [
(xlabelname, "@__x__values_original{%F}"),
(name, "@{%s}%s" % (name, number_format)),
]
my_hover.formatters = {"__x__values_original": "datetime"}
else:
my_hover.tooltips = [
(xlabelname, "@__x__values_original"),
(name, "@{%s}%s" % (name, number_format)),
]
else:
my_hover.tooltips = hovertool_string
p.add_tools(my_hover)
return p
def lineplot(
p,
source,