├── .gitignore
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── NEWS.md
├── R
├── aaa.R
├── data.R
├── geom_posterior.R
├── ggdistribute-package.R
├── gghelpers.R
├── helpers.R
├── position_spread.R
├── stat_posterior_density.R
├── stats.R
├── theme.R
└── zzz.R
├── README.Rmd
├── README.md
├── cran-comments.md
├── data
└── sre.rda
├── ggdistribute.Rproj
├── inst
└── CITATION
├── man
├── GeomPosterior.Rd
├── annotate_corner.Rd
├── cmode.Rd
├── data_normal_sample.Rd
├── dmode.Rd
├── example_plot.Rd
├── figures
│ ├── README-candy_wrappers-1.png
│ ├── README-rainbow_hills-1.png
│ ├── README-space_ships-1.png
│ └── README-turtle_snails-1.png
├── ggdistribute-package.Rd
├── hdi.Rd
├── label_plot.Rd
├── mejr_geom_defaults.Rd
├── mejr_palette.Rd
├── position_spread.Rd
├── post_int.Rd
├── posterior_plot.Rd
├── scale_add.Rd
├── show_colors.Rd
├── sre.Rd
├── test_mejr_theme.Rd
├── theme_mejr.Rd
└── trim_ends.Rd
├── tests
├── testthat.R
└── testthat
│ ├── test_geom_posterior.R
│ ├── test_position_spread.R
│ └── test_stat_density.R
└── vignettes
└── geom_posterior.Rmd
/.gitignore:
--------------------------------------------------------------------------------
1 | Meta
2 | doc
3 | .html
4 | .httr-oauth
5 | .junk
6 | .Rapp.history
7 | .Rbuildignore
8 | .RData
9 | .Rhistory
10 | .vscode
11 | *-Ex.R
12 | *.dll
13 | *.DS_Store
14 | *.knit.md
15 | *.o
16 | *.so
17 | *.utf8.md
18 | /*_cache/
19 | /*.Rcheck/
20 | /*.tar.gz
21 | /cache/
22 | src-i386
23 | src-x64
24 | vignettes/*.html
25 | vignettes/*.pdf
26 |
27 | ggdistribute.code-workspace
28 | .Rproj.user
29 | CRAN-RELEASE
30 |
--------------------------------------------------------------------------------
/DESCRIPTION:
--------------------------------------------------------------------------------
1 | Package: ggdistribute
2 | Title: A 'ggplot2' Extension for Plotting Unimodal Distributions
3 | Version: 1.0.3
4 | Date: 2018-11-15
5 | Authors@R: c(
6 | person("Joseph M.", "Burling",
7 | email = "josephburling@gmail.com",
8 | role = c("aut", "cre")))
9 | Description:
10 | The 'ggdistribute' package is an extension for plotting posterior or other
11 | types of unimodal distributions that require overlaying information about a
12 | distribution's intervals. It makes use of the 'ggproto' system to extend
13 | 'ggplot2', providing additional "geoms", "stats", and "positions."
14 | The extensions integrate with existing 'ggplot2' layer elements.
15 | URL: https://github.com/iamamutt/ggdistribute
16 | License: GPL-3
17 | Encoding: UTF-8
18 | LazyData: true
19 | Depends:
20 | R (>= 3.5.0)
21 | Imports:
22 | data.table,
23 | ggplot2 (>= 3.0.0),
24 | tibble,
25 | magrittr,
26 | grDevices,
27 | dplyr
28 | Suggests:
29 | knitr,
30 | testthat,
31 | rmarkdown,
32 | viridisLite,
33 | extrafont
34 | VignetteBuilder: knitr
35 | RoxygenNote: 6.1.1
36 | Roxygen: list(markdown=TRUE)
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/NAMESPACE:
--------------------------------------------------------------------------------
1 | # Generated by roxygen2: do not edit by hand
2 |
3 | export(annotate_corner)
4 | export(cmode)
5 | export(data_normal_sample)
6 | export(dmode)
7 | export(example_plot)
8 | export(geom_posterior)
9 | export(hdi)
10 | export(label_plot)
11 | export(mejr_geom_defaults)
12 | export(mejr_palette)
13 | export(position_spread)
14 | export(post_int)
15 | export(posterior_plot)
16 | export(show_colors)
17 | export(sre_data)
18 | export(stat_density_ci)
19 | export(theme_mejr)
20 | export(trim_ends)
21 | import(data.table)
22 | import(ggplot2)
23 | importFrom(grDevices,col2rgb)
24 | importFrom(grDevices,gray)
25 | importFrom(grDevices,rainbow)
26 | importFrom(grDevices,rgb)
27 | importFrom(magrittr,"%>%")
28 | importFrom(stats,density)
29 | importFrom(stats,ecdf)
30 | importFrom(stats,mad)
31 | importFrom(stats,median)
32 | importFrom(stats,na.omit)
33 | importFrom(stats,quantile)
34 | importFrom(stats,rgamma)
35 | importFrom(stats,rnbinom)
36 | importFrom(stats,rnorm)
37 | importFrom(stats,runif)
38 | importFrom(stats,sd)
39 | importFrom(utils,capture.output)
40 | importFrom(utils,modifyList)
41 |
--------------------------------------------------------------------------------
/NEWS.md:
--------------------------------------------------------------------------------
1 | # ggdistribute 1.0.3
2 |
3 | * Change all occurences of `midline_color` to `midline` to avoid warnings for `_colour` parameters
4 |
5 | # ggdistribute 1.0.2
6 |
7 | * `show_colors()` theme update for ggplot2 2.3.0
8 |
9 | # ggdistribute 1.0.1
10 |
11 | * Fix R CMD Check notes
12 | * Align geoms to y axis
13 | * Extend README
14 | * Fix reverse in position_spread
15 |
16 | # ggdistribute 1.0.0
17 |
18 | * Upload initial version of package to GitHub
19 |
20 | # ggdistribute 0.0.0.9001
21 |
22 | * Added a `NEWS.md` file to track changes to the package.
23 |
--------------------------------------------------------------------------------
/R/aaa.R:
--------------------------------------------------------------------------------
1 | # "fix" R CMD check notes
2 | if (getRversion() >= "2.15.1") {
3 | utils::globalVariables(
4 | c(
5 | ".", ".__adj", ".__by_ht", ".__grp", ".__ht", ".__len", ".__max", ".__mid",
6 | ".__min", ".__n", ".__tmp", ".__y", "PANEL", "group", "grp_max", "grp_min", "x",
7 | "y", "ylower", "ymax", "ymin", "yupper"
8 | )
9 | )
10 | }
11 |
12 | if (getRversion() >= "3.1.0") {
13 | utils::suppressForeignCheck(
14 | c(
15 | ".", ".__adj", ".__by_ht", ".__grp", ".__ht", ".__len", ".__max", ".__mid",
16 | ".__min", ".__n", ".__tmp", ".__y", "PANEL", "group", "grp_max", "grp_min", "x",
17 | "y", "ylower", "ymax", "ymin", "yupper"
18 | )
19 | )
20 | }
21 |
--------------------------------------------------------------------------------
/R/data.R:
--------------------------------------------------------------------------------
1 | #' Raw SRE dataset
2 | #'
3 | #' @format Dataset is an object of class [tibble::tibble].
4 | #' @seealso [sre_data()]
5 | #' @return A dataset of [tibble::tibble].
6 | #' @examples
7 | #' sre
8 | #'
9 | #' sre_data()
10 | "sre"
11 |
12 |
13 | #' @describeIn sre create samples from sre data
14 | #' @param n number of samplers per effect and contrast
15 | #' @param seed set.seed number
16 | #' @export
17 | sre_data <- function(n=1000, seed=19850519) {
18 | set.seed(seed)
19 |
20 | # R CMD check
21 | effect <- contrast <- value <- NULL
22 |
23 | as_dtbl(get("sre")) %>%
24 | .[
25 | , .(value=sample(value, n, replace=TRUE)),
26 | .(effect, contrast)
27 | ] %>%
28 | tibble::as.tibble()
29 | }
30 |
31 |
32 | #' Testing dataset of grouped Normal distributions
33 | #'
34 | #' @param mu Means for each group. A [numeric] vector with the length
35 | #' corresponding to the number of groups.
36 | #' @param n Number of observations for each group. Length 1 [integer].
37 | #' @param sd_range The min and max to use for standard deviations. Length 2
38 | #' @param seed A seed value to generate the same sample. [numeric] vector.
39 | #' @return A [data.frame] with the following variables: `Group`, `Condition`,
40 | #' `value`.
41 | #' @export
42 | #' @examples
43 | #' data_normal_sample(0, 100)
44 | data_normal_sample <- function(mu=c(-0.5, 4), n=500L, sd_range=c(0.6, 1.4),
45 | seed=19850519) {
46 | set.seed(seed)
47 |
48 | k <- clip_range(length(mu), max=13)
49 | N <- n * k
50 |
51 | if (k == 1) {
52 | adj <- 0
53 | } else {
54 | adj <- median(diff(sort(unique(c(0, mu))))) / max(1, (k - 1))
55 | }
56 |
57 | adj <- c(-adj, adj)
58 | adj_len <- rep(adj, each=ceiling(n / 2))[1:n]
59 |
60 | value <- unlist(lapply(mu, function(x) {
61 | rnorm(n, mean=x, sd=runif(1L,
62 | min=sd_range[1],
63 | max=sd_range[2])) + adj_len
64 | }))
65 |
66 | scores <- unlist(lapply(mu, function(x) {
67 | sort(runif(2L, x + adj[1], x + adj[2]))
68 | }))
69 |
70 | Condition <- rep(LETTERS[seq_len(k)], each=n)
71 | Group <- sort(rep_len(letters[seq_len(k * 2)], N))
72 | GroupScore <- rep(scores, each=ceiling(N / k / 2))[1:N]
73 |
74 | tibble::tibble(Condition, Group, GroupScore, value)
75 | }
76 |
77 | ggdist_data <- function(n=500, j=3, k=2, na.rm=TRUE, seed=20130110) {
78 | set.seed(seed)
79 | j <- max(min(j, 26), 1)
80 | k <- max(min(k, 26), 1)
81 | n_jk <- j * k
82 | n_i <- round(max(1, n / n_jk))
83 |
84 | # R CMD check
85 | jk_i <- qmin <- qmax <- value <- variable <- NULL
86 |
87 | dt <- expand.grid(j=seq_len(j), k=seq_len(k)) %>%
88 | as.data.table() %>%
89 | rep(n_i) %>%
90 | .[, `:=`(j_discrete=LETTERS[j], k_discrete=letters[k])] %>%
91 | .[order(j, k)] %>%
92 | .[, value := rnorm(.N, 2 * j, k^.618), .(j, k)] %>%
93 | cbind(.[, probit_tbl(value, n_jk)]) %>%
94 | .[, variable := runif(.N, qmin, qmax), .(qmin, qmax)] %>%
95 | .[, `:=`(`jk_i`=.GRP), .(j, k)] %>%
96 | .[`jk_i` == max(`jk_i`), value := NA] %>%
97 | .[, .__tmp := min(variable, na.rm=TRUE)] %>%
98 | .[j == min(2, max(j)), variable := {
99 | variable[which.min(variable)] <- .__tmp[1]
100 | variable
101 | }] %>%
102 | .[order(j, k, variable)] %>%
103 | .[1, variable := min(.__tmp, na.rm=TRUE)] %>%
104 | .[, .__tmp := NULL] %>%
105 | .[, I := 1:.N]
106 |
107 |
108 | if (!na.rm) {
109 | return(tibble::as.tibble(dt))
110 | }
111 |
112 | dt[!is.na(value), ] %>%
113 | tibble::as.tibble()
114 | }
115 |
--------------------------------------------------------------------------------
/R/geom_posterior.R:
--------------------------------------------------------------------------------
1 | # Posterior layer wrapper -------------------------------------------------
2 |
3 | #' @describeIn GeomPosterior geom_posterior Posterior Geom
4 | #' @export
5 | geom_posterior <- function(mapping=NULL, data=NULL, stat="DensityCI", position="spread",
6 | ..., draw_ci=TRUE, draw_sd=TRUE, midline="#767698",
7 | brighten=TRUE, mirror=FALSE, interp_thresh=NULL, na.rm=FALSE,
8 | show.legend=NA, inherit.aes=TRUE) {
9 | layer(
10 | geom=GeomPosterior, stat=stat, data=data, mapping=mapping, position=position,
11 | show.legend=show.legend, inherit.aes=inherit.aes,
12 | params=list(
13 | draw_ci=draw_ci, draw_sd=draw_sd, midline=midline,
14 | mirror=mirror, brighten=brighten, interp_thresh=interp_thresh,
15 | na.rm=na.rm, ...
16 | )
17 | )
18 | }
19 |
20 | # ggproto object ----------------------------------------------------------
21 |
22 | GeomPosterior <- ggproto(
23 | "GeomPosterior", Geom,
24 | default_aes=aes(
25 | weight=1, color="#585872", fill="#8989B2", size=0.5,
26 | alpha=NA, linetype="solid", vjust=1
27 | ),
28 | required_aes=c("x", "y"), non_missing_aes=character(),
29 | optional_aes=c("xmin", "cil", "sdl", "mid", "sdu", "ciu", "xmax"),
30 | draw_key=draw_key_polygon,
31 |
32 |
33 | setup_data=function(self, data, params) {
34 | if (!("y" %Names?% data) && "count" %Names?% data) {
35 | warning("Missing `y` in aesthetics. Defaulting to `count`", call.=FALSE)
36 | data$y <- data$count
37 | }
38 |
39 | mirror <- params$mirror %NA% FALSE
40 |
41 | if (is.null(params$vjust) && mirror) {
42 | params$vjust <- 0.5
43 | }
44 |
45 | compute_vjust(data, "y", params$vjust)
46 | },
47 |
48 | draw_group=function(self, data, ..., # panel_scales, coord,
49 | draw_ci=TRUE, draw_sd=TRUE, midline="#767698",
50 | brighten=TRUE, mirror=FALSE, interp_thresh=NULL) {
51 | if (nrow(data) == 1) {
52 | return(zeroGrob())
53 | }
54 |
55 | # handle NA options
56 | draw_ci <- draw_ci %NA% FALSE
57 | draw_sd <- draw_sd %NA% FALSE
58 |
59 | if (is.null(midline)) {
60 | midline <- first_non_na(data$colour)
61 | }
62 |
63 | midline <- midline %NA% NA
64 | brighten <- brighten %NA% FALSE
65 | mirror <- mirror %NA% FALSE
66 |
67 | warn <- is.finite(interp_thresh %:% Inf) %?% FALSE %:% TRUE
68 | interp_thresh <- interp_thresh %:% 0.01
69 |
70 | if (draw_ci) {
71 | assert_names(
72 | c("cil", "ciu"), data, "No confidence intervals found.",
73 | " Set `draw_ci=FALSE` to remove this segment or use ",
74 | "`stat_density_ci` to compute this variable automatically."
75 | )
76 | }
77 |
78 | if (draw_sd) {
79 | assert_names(
80 | c("sdl", "sdu"), data, "No SD intervals found.",
81 | " Set `draw_sd=FALSE` to remove this segment or use ",
82 | "`stat_density_ci` to compute this variable automatically."
83 | )
84 | }
85 |
86 | dt <- as_dtbl(data, copy=TRUE) %>%
87 | set_range_data("x", names=c("xmin", "xmax"), force_cols=FALSE, copy=FALSE) %>%
88 | set_range_data("y", names=c("ymin", "ymax"), force_cols=FALSE, copy=FALSE) %>%
89 | set_range_data(
90 | "y",
91 | names=c("grp_min", "grp_max"), force_cols=TRUE, copy=FALSE
92 | )
93 |
94 | params <- setup_posterior_params(
95 | dt,
96 | draw_ci=draw_ci, draw_sd=draw_sd, midline=midline,
97 | mirror=mirror, brighten=brighten, interp_thresh=interp_thresh, warn=warn
98 | )
99 |
100 | ggname(
101 | "geom_posterior",
102 | grid::gTree(children=do.call(grid::gList, c(
103 | get_posterior_segment_grobs(
104 | dt, params, ...
105 | ),
106 | get_posterior_line_grobs(
107 | dt, params, ...
108 | )
109 | )))
110 | )
111 | }
112 | )
113 |
114 | # subfunctions ------------------------------------------------------------
115 |
116 | setup_posterior_params <- function(data, ...) {
117 | c(..., setup_post_seg_params(data, ...), setup_post_line_params(data, ...))
118 | }
119 |
120 | setup_post_seg_params <- function(data, brighten, draw_ci, draw_sd, ...) {
121 | fill <- first_non_na(data$fill) %NA% NA
122 |
123 | brighten <- if (is.logical(brighten)) {
124 | if (brighten) {
125 | c(4, 0, 1.333, 0, 4)
126 | } else {
127 | rep(0, 5L)
128 | }
129 | } else {
130 | rep_len(c(brighten, rev(brighten)[-1]), 5L)
131 | }
132 |
133 | segments <- c("xmin", "cil", "sdl", "sdu", "ciu", "xmax")
134 |
135 | if (!draw_ci) {
136 | segments[c(2, 5)] <- NA
137 | brighten[c(2, 4, 5)] <- NA
138 | }
139 |
140 | if (!draw_sd) {
141 | segments[c(3, 4)] <- NA
142 | brighten[c(3, 4)] <- NA
143 | }
144 |
145 | brighten <- na.omit(brighten)
146 | segments <- na.omit(segments)
147 | n <- length(brighten)
148 | segment_list <- structure(vector("list", n), .Names=segments[1:n])
149 |
150 | for (j in seq_len(n)) {
151 | cols <- segments[c(j, j + 1)]
152 | segment_list[[j]] <- list(
153 | lower_cut=first_non_na(data[[cols[1]]]) %:% NA_real_,
154 | upper_cut=first_non_na(data[[cols[2]]]) %:% NA_real_,
155 | fill=change_brightness(fill, brighten[j])
156 | )
157 | }
158 |
159 | c(list(segments=segment_list), fill=fill)
160 | }
161 |
162 | setup_post_line_params <- function(data, midline, draw_ci, draw_sd, ...) {
163 | colour <- first_non_na(data$colour) %NA% NA
164 |
165 | N <- 5
166 | line_pos <- c("cil", "sdl", "mid", "sdu", "ciu")
167 | line_widths <- c(1, 1.45, 2, 1.45, 1)
168 | line_colors <- rep(colour, N)
169 | line_colors[3] <- midline
170 |
171 | omit <- integer()
172 |
173 | if (!draw_ci) {
174 | omit <- append(omit, c(1, 5))
175 | }
176 |
177 | if (!draw_sd) {
178 | omit <- append(omit, c(2, 4))
179 | }
180 |
181 | keep <- which(!(seq_len(N) %in% omit))
182 | n <- length(keep)
183 | line_list <- structure(vector("list", n), .Names=line_pos[keep])
184 |
185 | for (j in seq_len(n)) {
186 | line_list[[j]] <- list(
187 | ci_column=line_pos[keep[j]], ci_color=line_colors[keep[j]],
188 | ci_lwd_adj=line_widths[keep[j]]
189 | )
190 | }
191 |
192 | c(list(lines=line_list), colour=colour)
193 | }
194 |
195 | get_posterior_data <- function(data, lower_cut=NULL, upper_cut=NULL, interp_thresh=NULL,
196 | mirror=FALSE, colour="#000000", fill=NA, warn=TRUE) {
197 | dt <- compute_post_seg_data(data, lower_cut, upper_cut, interp_thresh, warn)
198 |
199 | # find the bottom and top parts of the distribution to make a complete line
200 | assert_names(c("ymin", "ymax", "grp_max", "grp_min"), data)
201 |
202 | if (mirror) {
203 | dt[, `:=`(ylower=grp_max / 2 + grp_min - y / 2, yupper=grp_max / 2 + y / 2)]
204 |
205 | adj <- 0
206 | adj <- dt[
207 | , .(adj=mean(c(ymax, ymin)) - mean(c(grp_min, grp_max))),
208 | .(grp_min, grp_max, ymin, ymax)
209 | ] %>%
210 | .[, adj]
211 |
212 | dt[, `:=`(ylower=ylower + adj, yupper=yupper + adj)]
213 | } else {
214 | dt[, `:=`(ylower=grp_min, yupper=y)]
215 | }
216 |
217 | rbind(
218 | copy(dt) %>%
219 | .[, y := ylower] %>%
220 | .[order(x)],
221 | copy(dt) %>%
222 | .[, y := yupper] %>%
223 | .[order(-x)]
224 | ) %>%
225 | rm_temp_cols(c("colour", "fill")) %>%
226 | .[, `:=`(colour=colour, fill=fill)] %>%
227 | rbind(.[1, ])
228 | }
229 |
230 | compute_post_seg_data <- function(data, lower_cut=NULL, upper_cut=NULL,
231 | interp_thresh=NULL, warn=TRUE) {
232 | assert_names(c("xmin", "xmax", "x", "y"), data)
233 |
234 | interp_thresh <- interp_thresh %NA% Inf
235 |
236 | if (is.finite(interp_thresh) && interp_thresh <= 0) {
237 | stop("`interp_thresh` must be greater than 0.")
238 | }
239 |
240 | dt <- as_dtbl(data, copy=TRUE) %>%
241 | .[order(x, y), .(x, y)]
242 |
243 | static <- get_static_data(data, dt)
244 |
245 | # use xmin, xmax if not specifying horiz. cutoff points
246 | if (all_missing(lower_cut)) {
247 | lower_cut <- first_non_na(static$xmin)
248 | }
249 |
250 | if (all_missing(upper_cut)) {
251 | upper_cut <- first_non_na(static$xmax)
252 | }
253 |
254 | # check that density data is within cut thresholds
255 | within_range <- dt[, x >= lower_cut & x <= upper_cut]
256 | if (!any(within_range)) {
257 | warning(sprintf(
258 | "No data found between the cutoff points: (%.2f, %.2f)", lower_cut,
259 | upper_cut
260 | ), call.=FALSE)
261 | return(cbind(dt[1, ], static))
262 | }
263 |
264 | # do further interpolation if cut points are too far away from x density data
265 | within_range <- which(within_range)
266 |
267 | if (!c("cil", "ciu") %Names?% static) {
268 | ci_width <- static$xmax - static$xmin
269 | } else {
270 | ci_width <- static$ciu - static$cil
271 | }
272 |
273 | lower_gap <- (dt[within_range, min(x)] - lower_cut) / ci_width
274 | upper_gap <- (upper_cut - dt[within_range, max(x)]) / ci_width
275 |
276 | if (lower_gap + upper_gap > interp_thresh * 2) {
277 | if (warn) {
278 | gap_info <- sprintf(
279 | paste0(
280 | "The left side at %.2f is missing %.2f%%,",
281 | " and the right side at %.2f is missing %.2f%%",
282 | " of the CI width."
283 | ), lower_cut, lower_gap * 100,
284 | upper_cut, upper_gap * 100
285 | )
286 |
287 | warning(
288 | "Interpolating gaps. ", gap_info, " Try setting `n` to a higher value,",
289 | " setting `interp_thresh` to a smaller value, ",
290 | "or do `interp_thresh=NA` to turn off interpolation completely.",
291 | call.=FALSE
292 | )
293 | }
294 | dxy <- interp_low_res(
295 | dt$x, dt$y, lower_cut, upper_cut, max(1 / interp_thresh, 1024)
296 | )
297 | cbind(dxy, static)
298 | } else {
299 | cbind(dt[within_range, ], static)
300 | }
301 | }
302 |
303 | compute_post_line_data <- function(data, ci_column, ci_color="#000000", ci_lwd_adj=1) {
304 | line_column <- data[[ci_column]]
305 |
306 | if (all_missing(line_column)) {
307 | return(as_dtbl(data[1, ]))
308 | }
309 |
310 | assert_names(c("ylower", "yupper", "x"), data)
311 |
312 | dt <- as_dtbl(data)
313 | vline <- first_non_na(line_column)
314 |
315 | grob_data <- data.table(
316 | x=c(vline, vline), y=interp_vert_line(
317 | dt$x, dt$ylower, dt$yupper, vline
318 | ),
319 | group=c(vline, vline)
320 | )
321 |
322 | other_data <- get_static_data(dt, grob_data)
323 | grob_data <- cbind(rep(as_dtbl(other_data), nrow(grob_data)), grob_data)
324 | grob_data$colour <- ci_color
325 | grob_data$size <- grob_data$size * ci_lwd_adj
326 | grob_data$fill <- NA
327 | grob_data
328 | }
329 |
330 |
331 | get_posterior_line_grobs <- function(data, params, ...) {
332 | outline_pars <- params[c("interp_thresh", "mirror", "colour")]
333 | outline_pars$data <- data
334 | outline_pars$fill <- NA
335 | lines_data <- do.call(get_posterior_data, outline_pars)
336 |
337 | # path grabs of vertical lines
338 | ci <- lapply(params$lines, function(j) {
339 | j$data <- lines_data
340 | grob_data <- do.call(compute_post_line_data, j)
341 | if (nrow(grob_data) < 2) {
342 | return(zeroGrob())
343 | }
344 |
345 |
346 | return(GeomPath$draw_panel(grob_data, ...))
347 | })
348 |
349 | # path grob of density outline
350 | if (nrow(lines_data) < 2) {
351 | dens <- zeroGrob()
352 | } else {
353 | dens <- grob_posterior(lines_data, ..., use_fill=FALSE, use_color=TRUE)
354 | }
355 |
356 | c(ci, list(dens))
357 | }
358 |
359 | # polygon grobs of distribution segments
360 | get_posterior_segment_grobs <- function(data, params, ...) {
361 | shared_pars <- params[c("interp_thresh", "warn", "mirror")]
362 | shared_pars$colour <- NA
363 | shared_pars$data <- data
364 |
365 | lapply(params$segments, function(j) {
366 | segment <- do.call(get_posterior_data, c(shared_pars, j))
367 |
368 | grob_posterior(segment, ..., use_fill=TRUE, use_color=FALSE)
369 | })
370 | }
371 |
372 | grob_posterior <- function(data, ..., use_fill=FALSE, use_color=TRUE) {
373 | if (nrow(data) == 1) {
374 | return(zeroGrob())
375 | }
376 |
377 | munch_args <- structure(list(..., data), .Names=c("range", "coord", "data"))
378 | coords <- do.call(coord_munch, munch_args)
379 |
380 | # Sort by group to make sure that colors, fill, etc. come in same order
381 | coords <- coords[order(coords$group), ]
382 | first_rows <- coords[!duplicated(coords$group), ]
383 |
384 | ggname(
385 | "posterior_segment",
386 | grid::polygonGrob(
387 | coords$x, coords$y,
388 | default.units="native", id=coords$group,
389 | gp=grid::gpar(
390 | col=use_color %?% (first_rows$colour %:% NA) %:% NA,
391 | fill=use_fill %?% (first_rows$fill %:% NA) %:% NA,
392 | alpha=all_missing(first_rows$alpha) %?%
393 | 1 %:% ((first_rows$alpha) %:% 1), lwd=first_rows$size,
394 | lex=.pt, lty=first_rows$linetype
395 | )
396 | )
397 | )
398 | }
399 |
400 | compute_vjust <- function(data, axis, vjust=NULL) {
401 | if (is.null(vjust)) {
402 | return(data)
403 | }
404 |
405 | dt <- set_range_data(data, axis, force_cols=TRUE, copy=FALSE)
406 |
407 | if (length(unique(dt$group)) == 1) {
408 | spacing <- dt[, median(.__len, na.rm=TRUE)]
409 | } else {
410 | spacing <- dt[] %>%
411 | .[, .__grp := .GRP, .__min] %>%
412 | .[, .__len := unique_apply(.__min, .__grp, append_diff, NA)] %>%
413 | .[, median(.__len, na.rm=TRUE)]
414 | }
415 |
416 | if (!is.na(spacing)) {
417 | dt[, y := y - (spacing * (1 - vjust))]
418 | }
419 | rm_temp_cols(dt)
420 | }
421 |
422 | # misc --------------------------------------------------------------------
423 |
424 | interp_low_res <- function(x, y, from, to, n=128) {
425 | x_interp <- seq(from, to, length.out=n)
426 | interp_fun <- stats::approxfun(x, y)
427 |
428 | data.table(x=x_interp, y=interp_fun(x_interp))
429 | }
430 |
431 | interp_vert_line <- function(x, from, to, v) {
432 | c(stats::approxfun(x, from)(v), stats::approxfun(x, to)(v))
433 | }
434 |
--------------------------------------------------------------------------------
/R/ggdistribute-package.R:
--------------------------------------------------------------------------------
1 | # Package info ------------------------------------------------------------
2 |
3 | #' A 'ggplot2' Extension for Plotting Unimodal Distributions
4 | #'
5 | #' The `ggdistribute` package is an extension for plotting posterior or other
6 | #' types of unimodal distributions that require overlaying information about a
7 | #' distribution's intervals. It makes use of the `ggproto` system to extend
8 | #' `ggplot2`, providing additional "geoms", "stats", and "positions." The
9 | #' extensions integrate with existing `ggplot2` layer elements.
10 | #'
11 | #' Displaying the distributions relies heavily on stacking distributions using
12 | #' position_spread, which may not align with other geoms.
13 | #'
14 | #' @seealso [ggplot2::geom_density], [ggplot2::position_dodge]
15 | #'
16 | #' See `help(package = "ggdistribute")` for a list of functions.
17 | #'
18 | #' View vignettes with `browseVignettes(package ="ggdistribute")`.
19 | #'
20 | #' @import ggplot2
21 | #' @import data.table
22 | #' @importFrom magrittr "%>%"
23 | #' @importFrom grDevices col2rgb gray rainbow rgb
24 | #' @importFrom stats density ecdf mad median na.omit quantile rgamma rnbinom
25 | #' rnorm runif sd
26 | #' @importFrom utils capture.output modifyList
27 | #' @docType package
28 | #' @name ggdistribute-package
29 | NULL
30 |
31 |
32 | # GeomPosterior / StatDensityCI help -------------------------------------
33 |
34 |
35 | #' Geom for plotting posterior distributions
36 | #'
37 | #' This geom may be used to plot the density of any type of numeric variable but
38 | #' the displayed intervals may not be informative if the distribution deviates
39 | #' too much from a unimodal, symmetric distribution.
40 | #'
41 | #' @name GeomPosterior
42 | #'
43 | #' @inheritParams ggplot2::geom_violin
44 | #' @param geom Use to override the default connection between `geom_posterior`
45 | #' and `stat_density_ci`
46 | #' @param draw_ci *geom*. Toggles drawing of the confidence interval lines and
47 | #' segments.
48 | #' @param draw_sd *geom*. Toggles drawing of the standard deviation interval
49 | #' lines and segments.
50 | #' @param midline *geom*. Color of the vertical, center line. Set to `NA`
51 | #' to omit the line.
52 | #' @param brighten *geom*. Numeric adjustments to the fill color. A value above
53 | #' 1 increases brightness, below decreases. Should be of length 1 or 5,
54 | #' otherwise values are recycled
55 | #' @param interp_thresh *geom*. If the number of samples used to estimate the
56 | #' density is low, this will result in gaps between segments. This argument
57 | #' decides to interpolate points based on gap proportion for a segment.
58 | #' @param mirror *geom*. Show standard densities (`mirror=FALSE`) or horizontal
59 | #' violin densities (`mirror=TRUE`).
60 | #' @param stat Used to override the default connection between `geom_posterior`
61 | #' and `stat_density_ci`.
62 | #'
63 | #' @param center_stat *stat*. character string of method to compute the
64 | #' distribution's central tendency, such as `"median"`, `"mean"`, or `"mode"`.
65 | #' @param interval_type *stat*. method of computing the interval, either `"hdi"`
66 | #' or `"ci"`
67 | #' @param ci_width *stat*. Width of the distribution's confidence/highest
68 | #' density interval, e.g., 0.95
69 | #' @param trim If a value between 0 and 1 is given, trim the tails of `x` by
70 | #' some proportion according to `trim`. If `NULL` or `NA`, don't trim the
71 | #' tails. See [trim_ends()].
72 | #' @param cut The values to use for the start and end of the density estimation
73 | #' are `cut` bandwidths (e.g., `0.5*bw`) *beyond* the extremes of the data.
74 | #' This allows the estimated density to drop to approximately zero at the
75 | #' extremes.
76 | #' @param bw The smoothing bandwidth to be used. If numeric, the standard
77 | #' deviation of the smoothing kernel. If character, a rule to choose the
78 | #' bandwidth, as listed in [stats::bandwidth]. If the bandwidth character
79 | #' starts wit a `"."` (e.g., `".nrd0"`), then the average bandwidth will be
80 | #' calculated among all groups in a panel and used for each density estimate.
81 | #' @inheritParams ggplot2::stat_density
82 | #' @section Aesthetics:
83 | #'
84 | #' `geom_posterior` understands the following aesthetics (required aesthetics
85 | #' are in bold):
86 | #'
87 | #' - **x**
88 | #'
89 | #' - **y**
90 | #'
91 | #' - xmin
92 | #'
93 | #' - xmax
94 | #'
95 | #' - alpha - colour
96 | #'
97 | #' - fill
98 | #'
99 | #' - group
100 | #'
101 | #' - linetype
102 | #'
103 | #' - size
104 | #'
105 | #' - weight
106 | #'
107 | #' @section Computed Variables:
108 | #'
109 | #' *stat_density_ci*:
110 | #'
111 | #' - density: density estimate from [stats::density]
112 | #'
113 | #' - scaled: Normalized density values: `density / max(density)`
114 | #'
115 | #' - count: Number of samples at density level: `(density / sum(density)) * n`
116 | #'
117 | #' - xmin: minimum value of `x` from the data
118 | #'
119 | #' - cil: cil cutoff value based on `ci_width`
120 | #'
121 | #' - sdl: central value minus 1 sd of `x`
122 | #'
123 | #' - mid: value of central tendency
124 | #'
125 | #' - sdu: central value plus 1 sd of `x`
126 | #'
127 | #' - ciu: ciu cutoff value based on `ci_width`
128 | #'
129 | #' - xmax: maximum value of `x` from the data
130 | #'
131 | #' *position_spread*
132 | #'
133 | #' - ymin: minimum value of `y` for each group in a panel.
134 | #'
135 | #' - ymax: maximum value of `y` for each group in a panel.
136 | #'
137 | #' @examples
138 | #' \donttest{
139 | #' library(ggplot2)
140 | #'
141 | #' x <- data_normal_sample(mu = c(-1, 0, 1), n = 500)
142 | #'
143 | #' p <- ggplot(x, aes(x = value))
144 | #'
145 | #' p + geom_posterior()
146 | #'
147 | #' p + geom_posterior(aes(y = Condition))
148 | #'
149 | #' p + geom_posterior(aes(y = GroupScore, fill = Condition))
150 | #'
151 | #' p + geom_posterior(aes(y = GroupScore, fill = Group),
152 | #' brighten = c(1.3, 0, -1.3),
153 | #' position = position_spread(
154 | #' height=0.5,
155 | #' padding = 0))
156 | #'
157 | #' }
158 | #' @md
159 | NULL
160 |
161 | #' Print an example of the package functions
162 | #'
163 | #' @return NULL
164 | #' @export
165 | example_plot <- function() {
166 | # color palette
167 | colors <- mejr_palette()
168 |
169 | ggplot(sre_data(5000), aes_string(y="effect")) +
170 |
171 | # ggdistribute specific elements -------------------------------------------
172 | geom_posterior(
173 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174 | # geom_posterior() aesthetics mappings
175 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176 | aes_string(x="value", fill="contrast"),
177 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178 | # options passed to stat_density_ci() for estimating intervals
179 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
180 | interp_thresh=.001, # threshold for interpolating segment gaps
181 | center_stat="median", # measure of central tendency
182 | ci_width=0.90, # width corresponding to CI segments
183 | interval_type="ci", # quantile intervals not highest density interval
184 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
185 | # options passed to stat_density_ci() for estimating density
186 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
187 | bw=".nrd0", # bandwidth estimator type
188 | adjust=1.5, # adjustment to bandwidth
189 | n=1024, # number of samples in final density
190 | trim=.005, # trim `x` this proportion before estimating density
191 | cut=1.5, # tail extension for zero density estimation
192 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193 | # geom_posterior() options
194 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195 | draw_ci=TRUE, # toggle showing confidence interval parts
196 | draw_sd=TRUE, # toggle showing standard deviation parts
197 | mirror=FALSE, # toggle horizontal violin distributions
198 | midline=NULL, # line displaying center of dist. (NULL=aes color)
199 | brighten=c(3, 0, 1.333), # additive adjustment of segment fill colors
200 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201 | # position_spread() options
202 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
203 | position=position_spread(
204 | reverse=TRUE, # order of spreaded groups within panels
205 | padding=0.3, # shrink heights of distributions
206 | height="panel" # scale by heights within panels
207 | ), #
208 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
209 | # standard ggplot layer options
210 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
211 | size=0.15, color=colors$gray, vjust=0.7, show.legend=FALSE
212 | ) +
213 |
214 | # standard ggplot2 elements ------------------------------------------------
215 | geom_vline(alpha=0.5, color=colors$gray, size=0.333, linetype=1, xintercept=0) +
216 | scale_x_continuous(breaks=seq(-1, 1, .05)) +
217 | facet_grid("contrast ~ .", scales="free_y", space="free_y") +
218 | scale_fill_manual(values=c(colors$yellow, colors$magenta, colors$cyan)) +
219 | labs(x="Difference in accuracy (posterior predictions)") +
220 | theme(
221 | legend.position="none", strip.text.y=element_text(angle=0, hjust=0.5),
222 | panel.border=element_rect(fill=NA, color=colors$lightgray, size=0.67),
223 | panel.grid=element_blank(), panel.ontop=FALSE, axis.title.y=element_blank(),
224 | plot.margin=margin(t=2, r=4, b=2, l=2, unit="pt")
225 | )
226 | }
227 |
--------------------------------------------------------------------------------
/R/gghelpers.R:
--------------------------------------------------------------------------------
1 | #' Print a small example plot with geom_posterior
2 | #'
3 | #' @param data A dataset to use, called at the top layer within `ggplot`.
4 | #' @param x A character string of the `x` axis variable name (e.g., values
5 | #' making up the distribution).
6 | #' @param y A grouping variable for generating groups of distributions. Defaults
7 | #' to `..count..` for no groups and displays the density as counts of the
8 | #' number of samples for the value of `x`.
9 | #' @param ... Additional arguments passed to [geom_posterior()].
10 | #'
11 | #' @return Object of class `gg`, `ggplot`.
12 | #' @export
13 | #' @examples
14 | #' # Generate a basic example plot if no data is specified.
15 | #' posterior_plot()
16 | posterior_plot <- function(data, x, y="..count..", ...) {
17 | if (missing(data)) {
18 | data <- data_normal_sample(0)
19 | x <- "value"
20 | y <- "..count.."
21 | }
22 |
23 | ggplot(data, aes_string(x=x, y=y)) + geom_posterior(...)
24 | }
25 |
26 | ggname <- function(prefix, grob) {
27 | grob$name <- grid::grobName(grob, prefix)
28 | grob
29 | }
30 |
31 | res_adjust <- function(x, scale_res=1, zero=FALSE) {
32 | x + (resolution(x, zero) * scale_res)
33 | }
34 |
35 | #' scale and add
36 | #'
37 | #' @param base_size start value
38 | #' @param amount multiple by
39 | #' @param adj add after
40 | #' @return numeric
41 | scale_add <- function(base_size, amount=1, adj=0) {
42 | (base_size * amount) + adj
43 | }
44 |
45 | set_range_data <- function(data, axis=c("x", "y"), by="group", force_cols=FALSE,
46 | names=NULL, copy=TRUE) {
47 | axis <- match.arg(axis)
48 | do_ops <- structure(list(min, max, function(x) {
49 | diff(range(x))
50 | }), .Names=c(".__min", ".__max", ".__len"))
51 |
52 | if (!is.null(names)) {
53 | do_ops <- do_ops[seq_along(names)]
54 | names(do_ops) <- names
55 | }
56 |
57 | dt <- as_dtbl(data, copy=copy)
58 |
59 | Map(function(n, f) {
60 | if (force_cols || all_missing(data[[n]])) {
61 | dt[, eval(n) := f(get(axis)), by=eval(by)]
62 | }
63 | }, names(do_ops), do_ops)
64 |
65 | if (copy) {
66 | as.data.frame(dt)
67 | } else {
68 | dt
69 | }
70 | }
71 |
72 | has_multiple_discrete <- function(data, scales, axis=c("x", "y")) {
73 | axis <- match.arg(axis)
74 | if (is.null(scales[[axis]]) || !scales[[axis]]$is_discrete()) {
75 | return(FALSE)
76 | }
77 |
78 | if (is.null(data[[axis]])) {
79 | return(FALSE)
80 | }
81 |
82 | length(unique(data[[axis]])) > 1
83 | }
84 |
85 | split_discrete_by_group <- function(data, scales, axis=c("x", "y")) {
86 | axis <- match.arg(axis)
87 |
88 | if (!("y" %Names?% data)) {
89 | return(data)
90 | }
91 |
92 | assert_names("group", data)
93 |
94 | dt <- as_dtbl(data)
95 |
96 | if (is.null(dt[[axis]])) {
97 | dt <- dt[order(group)]
98 | } else {
99 | dt <- dt[order(get(axis), group)]
100 | }
101 |
102 | dt[, .__grp := {
103 | if (has_multiple_discrete(.SD, scales, axis)) {
104 | paste0(group, .SD[[axis]])
105 | } else {
106 | paste0(group, 1)
107 | }
108 | }, group] %>%
109 | .[, group := .GRP, .__grp] %>%
110 | rm_temp_cols()
111 | }
112 |
113 | axis_is_within <- function(min1, max1, min2, max2) {
114 | m <- matrix(c(min1, min2, max1, max2, max1 - min1, max2 - min2), nrow=2)
115 | m <- m[order(-m[, 3]), ]
116 | m[1, 1] <= m[2, 1] & m[1, 2] >= m[2, 2]
117 | }
118 |
119 | # Check for overlap
120 | get_overlaps <- function(data, axis=c("x", "y"), tol=-1e-04) {
121 | axis <- match.arg(axis)
122 | assert_names(c(axis, "group"), data)
123 | dt <- as_dtbl(data)
124 |
125 | if (!("PANEL" %Names?% data)) {
126 | dt$PANEL <- 1L
127 | }
128 |
129 | minmax <- set_range_data(dt, axis, force_cols=TRUE, copy=FALSE) %>%
130 | .[!is.na(.__min) & !is.na(.__max), .(.__grp=.GRP), .(.__min, .__max, group)]
131 |
132 | rm_temp_cols(dt)
133 |
134 | n_grps <- length(unique(minmax$group))
135 |
136 | if (n_grps == 1) {
137 | pairs <- matrix(c(1, 1), ncol=2)
138 | } else {
139 | pairs <- t(utils::combn(n_grps, 2))
140 | }
141 |
142 | calc_vals <- list(
143 | pair_height=NA_real_, sep_height=NA_real_, space=NA_real_,
144 | space_ratio=NA_real_, scaled_space=NA_real_, overlap=NA, within=NA
145 | )
146 |
147 | # R CMD check
148 | h1 <- h2 <- i1 <- i2 <- max1 <- max2 <- min1 <- min2 <- NULL
149 |
150 | overlap_data <- as_dtbl(pairs) %>%
151 | setnames(c("V1", "V2"), c("i1", "i2")) %>%
152 | .[, I := .I] %>%
153 | .[, `:=`(
154 | min1=minmax$.__min[match(i1, minmax$.__grp)],
155 | max1=minmax$.__max[match(i1, minmax$.__grp)],
156 | min2=minmax$.__min[match(i2, minmax$.__grp)],
157 | max2=minmax$.__max[match(i2, minmax$.__grp)],
158 | group1=minmax$group[match(i1, minmax$.__grp)],
159 | group2=minmax$group[match(i2, minmax$.__grp)]
160 | )] %>%
161 | .[, `:=`("h1"=max1 - min1, "h2"=max2 - min2)] %>%
162 | .[, `:=`(i1=NULL, i2=NULL)] %>%
163 | .[, eval(names(calc_vals)) := lapply(calc_vals, identity)]
164 |
165 | if (n_grps == 1) {
166 | return(as.data.frame(overlap_data))
167 | }
168 |
169 | # R CMD check
170 | overlap <- pair_height <- scaled_space <- sep_height <- space <- space_ratio <- NULL
171 |
172 | overlap_data[] %>%
173 | .[, pair_height := max(max1, max2) - min(min1, min2), I] %>%
174 | .[, sep_height := h1 + h2] %>%
175 | .[, space := pair_height - sep_height] %>%
176 | .[, space_ratio := pair_height / sep_height] %>%
177 | .[space < 0 | space_ratio < 1, scaled_space := scale(c(0, space))[-1]] %>%
178 | .[is.na(scaled_space), scaled_space := 0] %>%
179 | .[, overlap := scaled_space < tol] %>%
180 | .[, within := axis_is_within(min1, max1, min2, max2), I] %>%
181 | as.data.frame()
182 | }
183 |
184 | rescale_groups <- function(data, axis=c("x", "y"), min_col=".__min", ht_col=".__len",
185 | scaler=0, by=NULL) {
186 | axis <- match.arg(axis)
187 | assert_names(unique(c("group", min_col, ht_col, axis)), data)
188 |
189 | dt <- as_dtbl(data)
190 | dt[, .__by_ht := get(ht_col)]
191 | by_grp <- by
192 |
193 | if (is.numeric(by)) {
194 | dt[, .__by_ht := by]
195 | by_grp <- NULL
196 | }
197 |
198 | dt[] %>%
199 | .[, .__adj := scaler * max(.__by_ht), by=eval(by_grp)] %>%
200 | .[, eval(axis) := rescale_as_other(
201 | get(axis), c(get(min_col), get(ht_col) - .__adj + get(min_col))
202 | ),
203 | by=c("group", min_col, ht_col)
204 | ] %>%
205 | .[]
206 | }
207 |
208 | check_padding <- function(x, size, padding, mult=1.5) {
209 | res <- resolution(x, FALSE) * mult
210 | max_ht <- max(size, na.rm=TRUE)
211 | shrunken_size <- max_ht - (padding * max_ht)
212 |
213 | if (shrunken_size > -res & shrunken_size < res) {
214 | warning("Paddding too large. Data compressed smaller than resolution.", call.=FALSE)
215 | return(0)
216 | }
217 | padding
218 | }
219 |
220 | rm_temp_cols <- function(data, temp_names=NULL) {
221 | if (is.null(temp_names)) {
222 | temp_names <- c(
223 | ".__adj", ".__by_ht", ".__grp", ".__ht", ".__len", ".__max_x", ".__max_y",
224 | ".__max", ".__mid", ".__min_x", ".__min_y", ".__min", ".__n", ".__tmp", ".__y"
225 | )
226 | }
227 |
228 | temp_names <- temp_names %Names% data
229 |
230 | if (is_none(temp_names)) {
231 | return(data)
232 | }
233 |
234 | as_dtbl(data) %>%
235 | .[, eval(temp_names) := NULL] %>%
236 | .[]
237 | }
238 |
239 |
240 | # colorspace --------------------------------------------------------------
241 |
242 |
243 | #' plot and show hex values of colors
244 | #'
245 | #' @param colors character vector of hex value colors
246 | #' @param show.legend show the legend with hex values (logical)
247 | #' @param ncols number of columns in the plot
248 | #' @param alpha set alpha level for all colors
249 | #'
250 | #' @return A plot with the index of the color in the tile
251 | #' @export
252 | #'
253 | #' @examples
254 | #' show_colors(mejr_palette())
255 | #' show_colors(topo.colors(25))
256 | #' show_colors(cm.colors(64), FALSE)
257 | #' show_colors(viridisLite::viridis(15), alpha = .8)
258 | show_colors <- function(colors, show.legend=TRUE, ncols=NULL, alpha=NA) {
259 | if (missing(colors)) {
260 | colors <- rainbow(10)
261 | }
262 |
263 | n <- length(colors)
264 |
265 | if (n <= 0) {
266 | warning("no colors to plot")
267 | }
268 |
269 | if (!is.null(ncols)) {
270 | ncols <- max(c(1L, ncols))
271 | } else {
272 | ncols <- sqrt(n)
273 | if (ncols != as.integer(ncols)) {
274 | ncols <- 1L
275 | }
276 | }
277 |
278 | # R CMD check
279 | i <- x <- y <- z <- l <- NULL
280 |
281 | rows <- ceiling(n / ncols)
282 | data <- expand.grid(x=seq_len(ncols), y=seq_len(rows))
283 | data <- data[with(data, order(y, x)), ]
284 | data$z <- factor(rep_len(colors, nrow(data)), levels=colors, labels=colors)
285 | data$i <- rep_len(1:n, nrow(data))
286 | data$l <- paste(data$i, data$z, sep=". ")
287 |
288 | ggplot(data, aes(x, y, fill=z)) + geom_raster(aes(fill=z), alpha=alpha) +
289 | scale_fill_manual(values=as.character(colors), breaks=data$z, labels=data$l) +
290 | geom_label(fill="white", hjust=0, nudge_x=-.45, colour=gray(0.5), aes(label=i)) +
291 | scale_y_reverse() +
292 | theme_void() + guides(fill=guide_legend(override.aes=list(alpha=1))) +
293 | theme(
294 | legend.position=ifelse(show.legend, "right", "none"), legend.box="vertical",
295 | legend.box.background=element_blank(), legend.text.align=0,
296 | legend.direction="vertical", legend.title=element_blank()
297 | )
298 | }
299 |
300 | gray2 <- function(black=127) {
301 | if (is.character(black)) {
302 | return(black)
303 | }
304 |
305 | if (black < 0 | black > 255) {
306 | warning(simpleWarning("black out of range [0, 255]"))
307 | }
308 |
309 | gray(clip_range(black, 0, 255) / 255)
310 | }
311 |
312 |
313 | change_brightness <- function(hex_color, adjust) {
314 | if (adjust == 0 || all_missing(hex_color)) {
315 | return(hex_color)
316 | }
317 |
318 | rgb_mat <- clip_range(col2rgb(hex_color), 1, 254)
319 | rgb_adj <- sigmoid(logit(rgb_mat / 255) + adjust)
320 |
321 | apply(rgb_adj, 2, function(i) {
322 | do.call(rgb, as.list(i))
323 | })
324 | }
325 |
326 |
327 | # unexported ggplot2 functions --------------------------------------------
328 |
329 |
330 | find_subclass <- function(super, class, env) {
331 | name <- paste0(super, camelize(class, first=TRUE))
332 | obj <- find_global(name, env=env)
333 | if (is.null(name)) {
334 | stop("No ", tolower(super), " called ", name, ".", call.=FALSE)
335 | } else {
336 | if (!inherits(obj, super)) {
337 | stop("Found object is not a ", tolower(super), ".", call.=FALSE)
338 | }
339 | }
340 | obj
341 | }
342 |
343 | find_global <- function(name, env, mode="any") {
344 | if (exists(name, envir=env, mode=mode)) {
345 | return(get(name, envir=env, mode=mode))
346 | }
347 | nsenv <- asNamespace("ggplot2")
348 | if (exists(name, envir=nsenv, mode=mode)) {
349 | return(get(name, envir=nsenv, mode=mode))
350 | }
351 | NULL
352 | }
353 |
354 | firstUpper <- function(s) {
355 | paste(toupper(substring(s, 1, 1)), substring(s, 2), sep="")
356 | }
357 |
358 |
359 | camelize <- function(x, first=FALSE) {
360 | x <- gsub("_(.)", "\\U\\1", x, perl=TRUE)
361 | if (first) {
362 | x <- firstUpper(x)
363 | }
364 | x
365 | }
366 |
--------------------------------------------------------------------------------
/R/helpers.R:
--------------------------------------------------------------------------------
1 | # missing/null values -----------------------------------------------------
2 |
3 | # check if x is NULL or zero length.
4 | # if allow_na=TRUE then also accepts all NA values as none.
5 | is_none <- function(x) {
6 | is.null(x) || length(x) < 1L
7 | }
8 |
9 | # check if all values are length zero or NA
10 | all_missing <- function(x) {
11 | is_none(x) || all(is.na(x))
12 | }
13 |
14 | # try to grab first non NA value in x, if none, return NULL
15 | first_non_na <- function(x) {
16 | val <- na.omit(x)[1] %:% NA
17 | if (is.na(val)) {
18 | return(NULL)
19 | }
20 | val
21 | }
22 |
23 | # return names of object that have non-zero chars
24 | non_empty_names <- function(x, na.rm=TRUE) {
25 | obj_names <- names(x)
26 | obj_names <- obj_names[nzchar(obj_names)]
27 | if (!na.rm) {
28 | return(obj_names)
29 | }
30 | Filter(Negate(is.na), obj_names)
31 | }
32 |
33 | assert_names <- function(required, from_obj, ...) {
34 | err <- list(...)
35 |
36 | if (is_none(err)) {
37 | fr <- sys.call(-1)
38 | fr <- (is.null(fr)) %?% ".GlobalEnv" %:% deparse(fr[1])
39 | err <- paste0(fr, ".")
40 | } else {
41 | err <- do.call(paste0, err)
42 | }
43 |
44 | if (!(required %Names?% from_obj)) {
45 | stop("names missing: ", paste0(required, collapse=", "), "\n", err, call.=FALSE)
46 | }
47 | }
48 |
49 | assert <- function(..., err=NULL, envir=parent.frame(), print) {
50 | exprs <- eval(substitute(alist(...)))
51 |
52 | force(envir)
53 |
54 | if (missing(print)) {
55 | if (is.null(err)) {
56 | print <- TRUE
57 | } else {
58 | print <- FALSE
59 | }
60 | }
61 |
62 | err <- paste0(err %:% "\b")
63 |
64 | lapply(exprs, function(e) {
65 | result <- eval(e, envir=envir)
66 | expr_str <- dQuote(deparse(e))
67 |
68 | if (print) {
69 | msg <- paste(err, "expression", expr_str, "failed")
70 | } else {
71 | msg <- err
72 | }
73 |
74 | if (!(length(result) == 1 && is.logical(result))) {
75 | stop("expression ", expr_str, " not logical", call.=FALSE)
76 | }
77 |
78 | if (!result) {
79 | stop(msg, call.=FALSE)
80 | }
81 |
82 | NULL
83 | })
84 |
85 | invisible()
86 | }
87 |
88 | char_or_names <- function(x) {
89 | if (!is.character(x)) {
90 | x <- non_empty_names(x)
91 | if (is_none(x)) {
92 | stop("Could not determine names from object", call.=FALSE)
93 | }
94 | }
95 | x
96 | }
97 |
98 | # special operators -------------------------------------------------------
99 |
100 | # If true then object else null
101 | #
102 | # @details This is primarily used in conjuction with the `%:%` operator. See
103 | # examples.
104 | # @param lhs logical scalar.
105 | # @param rhs object to return if `lhs` is `TRUE`.
106 | # @return object on `rhs` or `NULL`
107 | # @examples
108 | # \donttest{
109 | # `%:%` <- ggdistribute:::`%:%`
110 | # `%?%` <- ggdistribute:::`%?%`
111 | #
112 | # TRUE %?% 1 %:% 0 #> 1
113 | # FALSE %?% 1 %:% 0 #> 0
114 | #
115 | # x <- 0
116 | #
117 | # # expression returns whatever objects are wrapped in between %:%
118 | # (x == 0) %?% "y" %:% "n"
119 | # (x == 1) %?% c("y", "yes") %:% c("n", "No", "false")
120 | #
121 | # # ERROR: The %?% operator captured only 0, which is not logical.
122 | # # x == 0 %?% "y" %:% "n"
123 | #
124 | # # ERROR: The TRUE slot cannot return NULL because NULL is used to
125 | # # decide what to return in %:%
126 | # # `TRUE %?% NULL` and `FALSE %?% obj` would both return NULL.
127 | # # (x == 0) %?% NULL %:% "n"
128 | # }
129 | `%?%` <- function(lhs, rhs) {
130 | if (!is.logical(lhs) || length(lhs) > 1 || anyNA(lhs)) {
131 | stop("Value left of %?% must be logical, of length 1, and not NA.")
132 | }
133 |
134 | if (lhs) {
135 | if (is_none(rhs)) {
136 | stop(
137 | "Values right of %?% cannot return NULL or length zero.",
138 | " Try changing LHS to !LHS and reordering expresions after %?%."
139 | )
140 | }
141 | rhs
142 | } else {
143 | NULL
144 | }
145 | }
146 |
147 | # if LHS is NULL return RHS
148 | `%:%` <- function(lhs, rhs) {
149 | if (is.null(lhs)) {
150 | rhs
151 | } else {
152 | lhs
153 | }
154 | }
155 |
156 | # if LHS is NULL or length zero return RHS
157 | `%||%` <- function(lhs, rhs) {
158 | if (is_none(lhs)) {
159 | rhs
160 | } else {
161 | lhs
162 | }
163 | }
164 |
165 | # if LHS is NULL or length zero or all NA return RHS
166 | `%NA%` <- function(lhs, rhs) {
167 | if (all_missing(lhs)) {
168 | rhs
169 | } else {
170 | lhs
171 | }
172 | }
173 |
174 | `%Names%` <- function(lhs, rhs) {
175 | lhs <- char_or_names(lhs)
176 | lhs[lhs %chin% non_empty_names(rhs)]
177 | }
178 |
179 | `%!Names%` <- function(lhs, rhs) {
180 | lhs <- char_or_names(lhs)
181 | lhs[!(lhs %chin% non_empty_names(rhs))]
182 | }
183 |
184 | `%Names?%` <- function(lhs, rhs) {
185 | lhs <- char_or_names(lhs)
186 | all(lhs %chin% non_empty_names(rhs))
187 | }
188 |
189 | # transformations ---------------------------------------------------------
190 |
191 | range_sequence <- function(x, n) {
192 | limits <- range_no_inf(x)
193 | if (all_missing(limits)) {
194 | return(rep(NA, n))
195 | }
196 | seq(limits[1], limits[2], length.out=n)
197 | }
198 |
199 | # rescale x to the scale of y
200 | rescale_as_other <- function(x, y, scalar_adj=1) {
201 | limits <- range_no_inf(y)
202 | if (all_missing(limits)) {
203 | warning("x left as is. No range detected from y.")
204 | return(x)
205 | }
206 |
207 | center <- mean(limits)
208 | scale <- diff(limits)
209 |
210 | # if the min/max of y is the same then x will start at y and end at y+1
211 | if (scale <= 0) {
212 | scale <- (scalar_adj == 0) %?% 1 %:% scalar_adj
213 | center <- center + scalar_adj * 0.5
214 | }
215 |
216 | center + (norm_vec(x) - 0.5) * scale
217 | }
218 |
219 | # data objects ------------------------------------------------------------
220 |
221 | # data.frame/table is empty
222 | empty <- function(x) {
223 | is.null(x) || nrow(x) == 0 || ncol(x) == 0
224 | }
225 |
226 | as_dtbl <- function(x, copy=FALSE) {
227 | if (data.table::is.data.table(x)) {
228 | if (copy) {
229 | return(data.table::copy(x))
230 | }
231 | x
232 | } else {
233 | data.table::as.data.table(x)
234 | }
235 | }
236 |
237 | set_col_order <- function(x, first_names) {
238 | cols <- names(x)
239 | not_first <- cols[!cols %chin% first_names]
240 | data.table::setcolorder(x, c(first_names, not_first))
241 | invisible(x)
242 | }
243 |
244 | rep.data.table <- function(x, ...) {
245 | args <- list(...)
246 | if (length(args) < 1) {
247 | stop("must provide a `times, lenght.out, or each` argument")
248 | }
249 | n <- c(args[[1]], args$times, args$length.out, args$each)[1]
250 | if (!is.numeric(n)) {
251 | stop("second input argument must be numeric")
252 | }
253 | rbindlist(lapply(seq_len(n), function(...) {
254 | x
255 | }))
256 | }
257 |
258 | get_static_data <- function(from, ref=NULL) {
259 | from <- as_dtbl(from)
260 |
261 | if (is.null(ref)) {
262 | use_names <- non_empty_names(from)
263 | } else {
264 | use_names <- from %!Names% ref
265 | }
266 |
267 | if (length(use_names) < 1) {
268 | return(NULL)
269 | }
270 |
271 | is_static_df <- from[, lapply(.SD, function(i) {
272 | uniqueN(i) == 1
273 | }), .SDcols=use_names]
274 | static_cols <- names(Filter(isTRUE, is_static_df))
275 |
276 | if (is_none(static_cols)) {
277 | return(NULL)
278 | }
279 |
280 | as.data.frame(from[1, static_cols, with=FALSE])
281 | }
282 |
283 | # misc --------------------------------------------------------------------
284 |
285 | append_diff <- function(x, val=NA) {
286 | c(diff(x), val)
287 | }
288 |
289 |
290 | unique_apply <- function(x, i, FUN, ...) {
291 | if (is.null(i)) {
292 | i <- integer(length(x)) + 1L
293 | }
294 |
295 | if (!is.numeric(i)) {
296 | stop("i must be an integer index")
297 | }
298 |
299 | if (length(x) != length(i)) {
300 | stop("i must be the same size as x")
301 | }
302 |
303 | FUN <- match.fun(FUN)
304 | unq_i <- !duplicated(i)
305 | unq_v <- FUN(x[unq_i], ...)
306 | unq_v[i]
307 | }
308 |
309 | unique_simplex <- function(size_vec, grp_idx=NULL, offset_vec=0) {
310 | size <- size_vec - offset_vec
311 | unique_apply(size, grp_idx, function(x) {
312 | x / sum(x)
313 | })
314 | }
315 |
316 | function2chunk <- function(...) {
317 | functions <- as.character(match.call())[-1L]
318 | function_txt <- capture.output(dump(functions, "", control="all"))
319 | cat("\n\n```r\n")
320 | cat(function_txt, sep="\n")
321 | cat("\n```\n\n")
322 | }
323 |
--------------------------------------------------------------------------------
/R/position_spread.R:
--------------------------------------------------------------------------------
1 | # PositionSpread wrapper --------------------------------------------------
2 |
3 | #' Spread Overlapping Grobs Spread overlapping groups by shrinking them to fit
4 | #' within the data's `y` range.
5 | #'
6 | #' @param height One of `total` (default), `panel`, `single`, a numeric scalar
7 | #' value to give all geoms equal space, or a numeric vector the length of
8 | #' `panels*groups` for manually specifying the height of each group.
9 | #' @param reverse Reverse the order of segments within overlapping `y` ranges.
10 | #' @param padding Multiple of height. Will shrink/enlarge groups to fit within a
11 | #' region.
12 | #' @return NULL
13 | #' @export
14 | #' @examples
15 | #' library(ggplot2)
16 | #'
17 | #' x <- data.frame(y = rnorm(1000), x="", myGroup=sample(1:3, 1000, TRUE))
18 | #'
19 | #' ggplot(x, aes(x, y))+
20 | #' geom_point(aes(group=myGroup), position=position_spread(height = 0.5))
21 | position_spread <- function(height=NULL, reverse=FALSE, padding=0.2) {
22 | ggproto(NULL, PositionSpread, height=height, reverse=reverse, padding=padding)
23 | }
24 |
25 | # ggproto object ----------------------------------------------------------
26 |
27 | PositionSpread <- ggproto(
28 | "PositionSpread", Position,
29 | required_aes="y", height=NULL, reverse=FALSE,
30 | padding=0.2,
31 | setup_params=function(self, data) {
32 | height_pars <- standardize_height_param(data, self$height %NA%
33 | "single")
34 |
35 | list(
36 | height=height_pars$heights, custom=height_pars$custom,
37 | padding=self$padding %NA% 0, reverse=self$reverse %NA% FALSE
38 | )
39 | },
40 |
41 | compute_panel=function(data, params, scales) {
42 | as_dtbl(data) %>%
43 | transform_heights(heights=params$height, padding=params$padding) %>%
44 | spread_by_ymin(
45 | spreader=shrink_and_stack, reverse=params$reverse,
46 | padding=params$padding
47 | ) %>%
48 | rescale_overlapping(scales=scales, skip=params$custom) %>%
49 | set_col_order(c("PANEL", "group", "x", "y") %Names% data) %>%
50 | as.data.frame()
51 | }
52 | )
53 |
54 | # subfunctions ------------------------------------------------------------
55 | standardize_height_param <- function(data, height) {
56 | height_type <- c("num", "char")[c(is.numeric(height), is.character(height))]
57 |
58 | if (is_none(height_type)) {
59 | stop("Invalid height argument specified for position_spread: ", height, call.=FALSE)
60 | }
61 |
62 | assert_names(c("PANEL", "group", "y"), data)
63 |
64 | # R CMD check
65 | space <- uspace <- NULL
66 |
67 | height_type <- height_type[1]
68 | n_heights <- nrow(unique(data[, c("PANEL", "group")]))
69 | dt <- as_dtbl(data, copy=TRUE)
70 |
71 | heights <- switch(
72 | height_type,
73 | char={
74 | grouping <- height_char_groups(height[1])
75 |
76 | # check if only one group per panel
77 | lonely_groups <- dt[] %>%
78 | set_range_data("y", by=c("group", "PANEL"), force_cols=TRUE, copy=FALSE) %>%
79 | .[, .(.__n=length(unique(.__min))), PANEL] %>%
80 | .[, all(.__n == 1)]
81 |
82 | ht <- if (lonely_groups) {
83 | height <- dt[, .(.__len=max(.__max - (y - .__min))), PANEL] %>%
84 | .[, max(.__len, na.rm=TRUE)]
85 |
86 | rep_len(height, n_heights)
87 | } else {
88 | # get all individual heights ("single")
89 | height_data <- set_range_data(dt, "y", force_cols=TRUE, copy=FALSE) %>%
90 | # order by min and use only these variables
91 | .[order(.__min), .(PANEL, group, .__min, .__max, .__len)] %>%
92 | # unique data
93 | unique() %>% # group by common y min values
94 | .[, .__grp := .GRP, .(.__min)] %>%
95 | # space in between y groups (from min y to next groups min y)
96 | .[, space := unique_apply(.__min, .__grp, append_diff)] %>%
97 | # get last space for the top of the panel
98 | .[
99 | is.na(space),
100 | space := max(c(.[, max(space %NA% .__len, na.rm=TRUE)], .__len))
101 | ] %>%
102 | # pick the smallest space according to user group
103 | .[, uspace := min(space), by=grouping] %>%
104 | # height is the max of user heights or y group space
105 | .[, ht := max(c(.__len, uspace)), by=c(grouping, "uspace")]
106 |
107 | height_data$ht
108 | }
109 |
110 | ht
111 | }, num={
112 | n_user_heights <- length(height)
113 | if (n_user_heights != 1 && n_user_heights != n_heights) {
114 | warning("Height length was size ", n_user_heights, " but ", n_heights,
115 | " heights are required. ", "Recycling heights if any are missing.",
116 | call.=FALSE)
117 | }
118 |
119 | rep_len(height, n_heights)
120 | }, NULL
121 | )
122 |
123 | heights <- dt[, .(`.__ht`=heights[.GRP]), .(PANEL, group)]
124 | rm_temp_cols(data)
125 | list(heights=heights, type=height_type, custom=height_type == "num")
126 | }
127 |
128 | height_char_groups <- function(height_str=c("total", "panel", "single")) {
129 | switch(tolower(match.arg(height_str)), total=NULL, panel="PANEL",
130 | single=c("PANEL", "group"), NULL)
131 | }
132 |
133 | transform_heights <- function(data, heights, padding) {
134 | assert_names(c("group", "y"), data)
135 |
136 | as_dtbl(data) %>%
137 | merge(heights, by=c("PANEL", "group"), all.y=FALSE) %>%
138 | set_range_data("y", names=".__min", copy=FALSE) %>%
139 | rescale_groups("y", ht_col=".__ht") %>%
140 | rm_temp_cols()
141 | }
142 |
143 | spread_by_ymin <- function(data, spreader, ...) {
144 | assert_names(c("PANEL", "group", "y"), data)
145 |
146 | # NOTE: also creates the variables ymin, ymax in data
147 | as_dtbl(data) %>%
148 | set_range_data("y",
149 | by=c("PANEL", "group"), force_cols=TRUE,
150 | names=c("ymin", "ymax"), copy=FALSE) %>%
151 | .[, .__min := ymin] %>%
152 | .[, spreader(.SD, ...), .(.__min, PANEL)] %>%
153 | rm_temp_cols()
154 | }
155 |
156 | # shrink each group to fit within y range and stack on top of each other.
157 | # groups should be overlapping
158 | shrink_and_stack <- function(SD, reverse=FALSE, padding=0) {
159 | if (all(SD$group < 0)) {
160 | return(SD)
161 | }
162 |
163 | assert_names(c("ymin", "ymax"), SD)
164 |
165 | # must copy if as j within data.table
166 | dt <- as_dtbl(SD, copy=TRUE)
167 | dt[, .__len := ymax - ymin]
168 |
169 | n_groups <- length(unique(dt$group))
170 | padding <- check_padding(dt$y, dt$.__len, padding)
171 |
172 | if (n_groups <= 1) {
173 | return(rm_temp_cols(rescale_groups(dt, "y", min_col="ymin", scaler=padding)))
174 | }
175 |
176 | # stack order
177 | if ("x" %Names?% dt) {
178 | dt[, .__mid := -x]
179 | } else {
180 | dt[, .__mid := group]
181 | }
182 |
183 | dt <- dt[] %>%
184 | .[, .__mid := mean(range_no_inf(.__mid)), group] %>%
185 | .[order(-.__mid, -group, -y), ] %>%
186 | .[, `:=`(.__grp=.GRP), .(group)]
187 |
188 | if (reverse) {
189 | dt <- dt[order(-.__grp), .__grp := .GRP, .__grp]
190 | }
191 |
192 | pad_adj <- 1 - (padding / max(1, n_groups - 2))
193 |
194 | dt[] %>% # total height of data
195 | .[, .__len := diff(range_no_inf(y))] %>% # each overlapping groups height
196 | .[, .__ht := ymax - ymin] %>%
197 | # group heights sum to total height
198 | .[, .__len := .__len * unique_simplex(.__ht, .__grp)] %>%
199 | # shrink y by group height segments
200 | .[, .__y := rescale_as_other(y, c(0, .__len * pad_adj)), .(.__grp, .__len)] %>%
201 | # reposition y by stacking based on group height values
202 | .[, .__tmp := unique_apply(.__y * (1 / pad_adj), .__grp, csum_left)] %>%
203 | .[, y := .__y + .__tmp + ymin] %>%
204 | .[, `:=`(ymin=min(y), ymax=min(y) + .__len), .(.__grp)] %>% # junk
205 | rm_temp_cols()
206 | }
207 |
208 | rescale_overlapping <- function(data, scales, skip=FALSE) {
209 | if (skip || is.null(scales$y) || !scales$y$is_discrete()) {
210 | # don't change size of continuous scales or height specified manually
211 | return(data)
212 | }
213 |
214 | o_laps <- get_overlaps(data, "y")
215 |
216 | complete_overlap <- o_laps$within
217 |
218 | if (all_missing(complete_overlap)) {
219 | return(data)
220 | }
221 |
222 | which_overlaps <- o_laps$overlap[!complete_overlap]
223 |
224 | if (any(complete_overlap)) {
225 | warning("Sizes completely overlap with given height.")
226 | }
227 |
228 | if (!any(which_overlaps)) {
229 | return(data)
230 | }
231 |
232 | dt <- set_range_data(data, "y", force_cols=TRUE, copy=FALSE)
233 |
234 | o_laps <- o_laps[which_overlaps, ]
235 | o_laps <- o_laps[order(o_laps$sep_height), ]
236 | o_laps <- o_laps[which.min(o_laps$space), ]
237 |
238 | min_y <- c(o_laps$min1, o_laps$min2)
239 | y_ord <- order(min_y)
240 | min_y <- min_y[y_ord]
241 | max_y <- c(o_laps$max1, o_laps$max2)[y_ord]
242 | h_y <- c(o_laps$h1, o_laps$h2)[y_ord][1]
243 | shrink <- (max_y[1] - min_y[2]) / h_y
244 | h_adj <- 1.2 * h_y * dt[
245 | group %in% c(o_laps$group1, o_laps$group2),
246 | 1 - (resolution(y, FALSE) / diff(range_no_inf(y)))
247 | ]
248 |
249 | rm_temp_cols(rescale_groups(dt, "y", scaler=shrink, by=h_adj))
250 | }
251 |
--------------------------------------------------------------------------------
/R/stat_posterior_density.R:
--------------------------------------------------------------------------------
1 | # StatDensityCI wrapper ---------------------------------------------------
2 |
3 | #' @describeIn GeomPosterior stat_density_ci Computes a distribution density and
4 | #' confidence intervals for each group
5 | #' @export
6 | stat_density_ci <- function(mapping=NULL, data=NULL, geom="Posterior",
7 | position="spread", ..., center_stat="median", ci_width=0.9,
8 | interval_type="ci", bw="nrd0", adjust=1, kernel="gaussian",
9 | cut=1, n=1024, trim=0.01, na.rm=FALSE, show.legend=NA,
10 | inherit.aes=TRUE) {
11 | layer(
12 | data=data, mapping=mapping, stat=StatDensityCI, geom=geom, position=position,
13 | show.legend=show.legend, inherit.aes=inherit.aes,
14 | params=list(...,
15 | center_stat=center_stat, ci_width=ci_width,
16 | interval_type=interval_type, bw=bw, adjust=adjust, kernel=kernel,
17 | cut=cut, n=n, trim=trim, na.rm=na.rm)
18 | )
19 | }
20 |
21 |
22 | # ggproto object ----------------------------------------------------------
23 |
24 | StatDensityCI <- ggproto(
25 | "StatDensityCI", Stat,
26 | required_aes="x", default_aes=aes(y=..count..),
27 |
28 | setup_params=function(data, params) {
29 | params$bw <- calc_avg_bw(data, params$bw)
30 | params
31 | },
32 | compute_panel=function(self, data, scales, ...) {
33 | if (scales$x$is_discrete()) {
34 | stop("in stat_density_ci, `x` cannot be discrete.")
35 | }
36 |
37 | as_dtbl(data) %>%
38 | split_discrete_by_group(scales, "y") %>%
39 | .[, self$compute_group(.SD, ...), .(PANEL, group)] %>%
40 | as.data.frame()
41 | },
42 | compute_group=function(data, center_stat="median", ci_width=0.9,
43 | interval_type="ci", adjust=1, kernel="gaussian", cut=1,
44 | n=1024, bw="nrd0", trim=0.01, na.rm=FALSE, ...) {
45 | if (length(unique(data$x)) < 2) {
46 | warning("x contains a single unique value. Dropping group.")
47 | return(NULL)
48 | }
49 |
50 | # density coords
51 | dens <- compute_density(
52 | x=data$x, y=data$y, w=NULL, cut=cut, bw=calc_bw(
53 | data$x, bw
54 | ),
55 | adjust=adjust, kernel=kernel, n=n, trim=trim
56 | )
57 |
58 | if (all_missing(dens$x)) {
59 | return(NULL)
60 | }
61 |
62 | # confidence interval coords
63 | cint <- compute_conf_ints(data$x, center_stat, ci_width, interval_type)
64 |
65 | # combine with other data not used
66 | dist_data <- cbind(dens, cint)
67 | to_append <- get_static_data(data, dist_data)
68 |
69 | if (is.null(to_append)) {
70 | return(dist_data)
71 | }
72 |
73 | cbind(dist_data, to_append)
74 | }
75 | )
76 |
77 | # subfunctions ------------------------------------------------------------
78 |
79 | compute_density <- function(x, y=NULL, w=NULL, cut=1, bw="nrd0", adjust=1,
80 | kernel="gaussian", n=512, trim=NULL) {
81 | x <- is.null(trim) %?% x %:% trim_ends(x, trim, na.rm=TRUE)
82 | n_x <- length(x)
83 |
84 | missing_y <- all_missing(y)
85 | calc_options <- list(density=NA_real_, scaled=NA_real_, count=NA_real_)
86 | calc_list <- missing_y %?% calc_options %:% list(y=NA_real_)
87 |
88 | df <- c(x=NA_real_, calc_list, n=n_x)
89 |
90 | if (n_x < 2) {
91 | warning("Returning NA while trying to compute density. ",
92 | "`x` must be at least length 2, ", "or set `na.rm=TRUE`.",
93 | call.=FALSE)
94 | return(as.data.frame(df))
95 | }
96 |
97 | dcoord <- stats::density(
98 | x,
99 | weights=w, bw=bw, adjust=adjust, kernel=kernel, n=n, cut=cut
100 | )
101 |
102 | # actual number of samples
103 | n <- length(dcoord$y)
104 |
105 | # make sure zero density
106 | min_y <- which.min(dcoord$y)
107 |
108 | if (dcoord$y[min_y] > 0) {
109 | left <- min_y / (n / 2) < 1
110 | nearest_min_i <- seq(max(1, min_y - 1), min(n, min_y + 1))
111 | x_adj <- mean(diff(dcoord$x[nearest_min_i]))
112 | x_adj <- left %?% (-x_adj) %:% x_adj
113 | after <- left %?% (min_y - 1) %:% min_y
114 | n <- n + 1
115 |
116 | dcoord$x <- append(dcoord$x, dcoord$x[min_y] + x_adj, after)
117 | dcoord$y <- append(dcoord$y, 0, after)
118 | }
119 |
120 | # y will be taken from one of these calc cols if not in aes
121 | df$density <- dcoord$y
122 | df$scaled <- dcoord$y / max(dcoord$y)
123 | df$count <- norm_vec_sum(dcoord$y) * df$n
124 |
125 | # y is specified, position density at start of y
126 | if (!missing_y) {
127 | df$y <- min(y, na.rm=TRUE) + norm_vec_sum(dcoord$y)
128 | }
129 |
130 | df$x <- dcoord$x
131 |
132 | as.data.frame(df)
133 | }
134 |
135 | # x coords for cil ci, sd cil, mid, sd ciu, ciu ci
136 | compute_conf_ints <- function(x, center_stat=NULL, ci_width=NULL, interval_type=NULL) {
137 | interval_frame <- data.frame(
138 | mid=NA_real_, sdl=NA_real_, sdu=NA_real_, cil=NA_real_, ciu=NA_real_
139 | )
140 |
141 | # setup defaults from missing
142 | ci_width <- max(ci_width %NA% 0.9)
143 | center_stat <- center_stat %NA% "median"
144 | interval_type <- interval_type %NA% "ci"
145 |
146 | # compute interval line positions regardless of being drawn
147 | markers <- post_int(x, mid=center_stat, int=interval_type, widths=ci_width)
148 |
149 | # assign to data which are to be drawn
150 | interval_frame$mid <- markers$c
151 | interval_frame$cil <- markers$l.wide
152 | interval_frame$ciu <- markers$r.wide
153 | interval_frame$sdl <- markers$l.sd
154 | interval_frame$sdu <- markers$r.sd
155 |
156 | interval_frame
157 | }
158 |
159 | # bandwidth calculator for density
160 | calc_bw <- function(x, bw) {
161 | if (is.character(bw)) {
162 | if (length(x) < 2) {
163 | stop("need at least 2 points to select a bandwidth automatically", call.=FALSE)
164 | }
165 | bw <- switch(
166 | tolower(bw), nrd0=stats::bw.nrd0(x), nrd=stats::bw.nrd(x), ucv=stats::bw.ucv(x),
167 | bcv=stats::bw.bcv(x), sj= , `sj-ste`=stats::bw.SJ(x, method="ste"),
168 | `sj-dpi`=stats::bw.SJ(x, method="dpi"), stop("unknown bandwidth rule")
169 | )
170 | }
171 | bw
172 | }
173 |
174 | # average bandwidth across groups
175 | calc_avg_bw <- function(data, bw, grps="group") {
176 | # if NULL or NA then use individual bandwidth
177 | bw <- bw %NA% "nrd0"
178 |
179 | if (!grepl("^\\.", bw)) {
180 | return(bw)
181 | }
182 |
183 | bw_str <- sub(".", "", bw)
184 |
185 | as_dtbl(data) %>%
186 | .[!is.na(x), .(bw=calc_bw(x, bw_str)), by=grps] %>%
187 | .[, mean(bw, na.rm=TRUE)]
188 | }
189 |
--------------------------------------------------------------------------------
/R/stats.R:
--------------------------------------------------------------------------------
1 | # distribution functions --------------------------------------------------
2 |
3 |
4 | #' Posterior intervals
5 | #'
6 | #' Returns cutoff points from a posterior distribution
7 | #' @return data.table
8 | #'
9 | #' @param x Vector of numeric values. Typically a posterior sample.
10 | #' @param mid Central tendency estimator. Defaults to `"median"`. Other options
11 | #' include `"mean"` and `"mode"`.
12 | #' @param widths interval widths
13 | #' @param adj Bandwidth adjustment used only with the `"mode"` estimator. See
14 | #' [dmode].
15 | #' @param rope Region of practical equivalence. Check how much of the
16 | #' distribution is within rope value.
17 | #' @param warn Turn off warning for flat intervals found (multiple possible
18 | #' values)
19 | #' @param int interval type, either "hdi" or "ci"
20 | #' @export
21 | #' @examples
22 | #' x <- rpois(5000, 15)
23 | #' ints <- post_int(x, warn = FALSE)
24 | #' hist(x, br=50)
25 | #' abline(v=ints$c, col="cyan")
26 | #' abline(v=ints[, c("l.wide", "r.wide")], col="magenta")
27 | #'
28 | #' post_int(x, "median", warn = FALSE)
29 | #' post_int(x, "mean", warn = FALSE)
30 | #' post_int(x, "mode", adj=2, rope = c(14, 16), warn = FALSE)
31 | post_int <- function(x, mid=c("median", "mean", "mode"), int=c("hdi", "ci"),
32 | widths=c(.50, .95), adj=1.5, rope=NULL, warn=FALSE) {
33 | if (!is.vector(x)) {
34 | stop("`x` must be a vector.")
35 | }
36 |
37 | mid <- match.arg(mid)
38 | int <- match.arg(int)
39 |
40 | center <- NA_real_
41 | scale <- NA_real_
42 |
43 | # measure of central tendency
44 | switch(mid, "mean"={
45 | center <- mean(x)
46 | scale <- sd(x)
47 | }, "median"={
48 | center <- median(x)
49 | scale <- mad(x)
50 | }, "mode"={
51 | center <- dmode(x, adjust=adj)
52 | scale <- mad(x)
53 | }, NULL)
54 |
55 | # interval function as an unevaluated function call
56 | int_fun <- switch(
57 | int, "ci"={
58 | match.call(
59 | quantile,
60 | call("quantile",
61 | x=quote(x),
62 | probs=quote(c((1 - w) / 2, w + ((1 - w) / 2))), names=FALSE)
63 | )
64 | }, "hdi"={
65 | match.call(hdi, call("hdi", x=quote(x), prob=quote(w), warn=warn))
66 | }, NULL
67 | )
68 |
69 | # mass within 1 sd range
70 | area_sd <- prop_in_range(x, center - scale, center + scale)
71 |
72 | # width identifiers
73 | widths <- sort(widths)
74 | width_ids <- sprintf("%.0f", widths * 100)
75 | width_ids[which.max(widths)] <- "wide"
76 |
77 | # left/right values for each width
78 | intervals <- data.table::rbindlist(
79 | Map(function(w, i) {
80 | ints <- structure(
81 | Reduce(cbind, eval(int_fun)),
82 | dimnames=list(NULL, c("l", "r"))
83 | )
84 | data.table::data.table(interval=i, ints)
85 | }, c(widths, area_sd), c(width_ids, "sd"))
86 | )
87 |
88 | central <- interval <- NULL
89 |
90 | # reshape to multivariate format
91 | intervals <- intervals[order(-interval), ]
92 | intervals <- intervals[, central := mid]
93 | intervals <- data.table::dcast(
94 | intervals, central ~ interval,
95 | value.var=c("l", "r"), sep="."
96 | )
97 | intervals[, c := center]
98 | set_col_order(intervals, c("central", "c", "l.sd", "l.wide", "r.sd", "r.wide"))
99 |
100 | # get rope
101 | if (!is.null(rope)) {
102 | if (is.character(rope) && rope == "max") {
103 | rope <- c(intervals$l.wide, intervals$r.wide)
104 | }
105 | if (length(rope) != 2) {
106 | stop("ROPE must be a minimum and maximum value")
107 | }
108 | rope <- sort(rope)
109 | rope_mass <- prop_in_range(x, rope[1], rope[2])
110 | intervals[, `:=`(l.rope=rope[1], r.rope=rope[2], rope=rope_mass)]
111 | }
112 |
113 | as.data.frame(intervals)
114 | }
115 |
116 | #' Highest density interval
117 | #'
118 | #' This is a function that will calculate the highest density interval from a
119 | #' posterior sample.
120 | #'
121 | #' The default is to calcualte the highest 95 percent interval. It can be used
122 | #' with any numeric vector instead of having to use one of the specific MCMC
123 | #' classes. This function has been adapted from John K. Kruschke (2011). Doing
124 | #' Bayesian Data Analaysis: A Tutorial with R and BUGS.
125 | #'
126 | #' @param x Numeric vector of a distribution of data, typically a posterior
127 | #' sample
128 | #' @param prob Width of the interval from some distribution. Defaults to `0.95`.
129 | #' @param warn Option to turn off multiple sample warning message Must be in the
130 | #' range of `[0,1]`.
131 | #' @return Numeric range
132 | #' @export
133 | #' @examples
134 | #' x <- qnorm(seq(1e-04, .9999, length.out=1001))
135 | #' hdi_95 <- hdi(x, .95)
136 | #' hdi_50 <- hdi(x, .50)
137 | #'
138 | #' hist(x, br=50)
139 | #' abline(v=hdi_95, col="red")
140 | #' abline(v=hdi_50, col="green")
141 | #'
142 | #' x <- exp(seq(pi * (1 - (1/16)), pi, len = 1000))
143 | #' x <- c(x, rev(x)[-1])
144 | #' x <- c(-x, x)
145 | #' plot(sort(x), type="l")
146 | #' plot(density(x, adjust=0.25))
147 | #' abline(v=hdi(x, p=.49), col=2)
148 | #' abline(v=hdi(x, p=.50), col=3)
149 | hdi <- function(x, prob=0.95, warn=TRUE) {
150 | if (anyNA(x)) {
151 | stop("HDI: ", "x must not contain any NA values.", call.=FALSE)
152 | }
153 |
154 | N <- length(x)
155 |
156 | if (N < 3) {
157 | if (warn) {
158 | warning("HDI: ", "length of `x` < 3.", " Returning NAs", call.=FALSE)
159 | }
160 | return(c(NA_integer_, NA_integer_))
161 | }
162 |
163 | x_sort <- sort(x)
164 | window_size <- as.integer(floor(prob * length(x_sort)))
165 |
166 | if (window_size < 2) {
167 | if (warn) {
168 | warning("HDI: ", "window_size < 2.", " `prob` is too small or x does not ",
169 | "contain enough data points.", " Returning NAs.",
170 | call.=FALSE)
171 | }
172 | return(c(NA_integer_, NA_integer_))
173 | }
174 |
175 | lower <- seq_len(N - window_size)
176 | upper <- window_size + lower
177 |
178 | # vectorized difference between edges of cumulative distribution based on
179 | # scan_length. Values are arranged from left to right scanning.
180 | window_width_diff <- x_sort[upper] - x_sort[lower]
181 |
182 | # find minimum of width differences, check for multiple minima
183 | min_i <- which(window_width_diff == min(window_width_diff))
184 | n_candies <- length(min_i)
185 |
186 | if (n_candies > 1) {
187 | if (any(diff(sort(min_i)) != 1)) {
188 | if (warn) {
189 | warning("HDI: ", "Identical densities found along ",
190 | "different segments of the distribution.", " Choosing rightmost.",
191 | call.=FALSE)
192 | }
193 | min_i <- max(min_i)
194 | } else {
195 | min_i <- floor(mean(min_i))
196 | }
197 | }
198 |
199 | # get values based on minimum
200 | c(x_sort[min_i], x_sort[upper[min_i]])
201 | }
202 |
203 | #' Mode from density estimation
204 | #'
205 | #' Finds the mode using the [density] function and then obtains the maximum value.
206 | #'
207 | #' @param x Value vector. Numeric or integers.
208 | #' @param adjust Bandwidth adjustment. See [density].
209 | #'
210 | #' @examples
211 | #' x <- rchisq(1000, 3)
212 | #' hist(x, br=50)
213 | #' abline(v = dmode(x), col = "red")
214 | #' abline(v = median(x), col = "green")
215 | #' abline(v = mean(x), col = "blue")
216 | #' @export
217 | dmode <- function(x, adjust=1.5) {
218 | x <- trim_ends(x, 0.05, na.rm=TRUE)
219 | d <- density(x, n=1000, bw="SJ", adjust=adjust)
220 | d$x[which.max(d$y)]
221 | }
222 |
223 | #' Mode from counting frequency
224 | #'
225 | #' Finds the most frequent value from a vector of discrete values
226 | #'
227 | #' @param x an integer vector
228 | #'
229 | #' @return scalar integer value
230 | #' @export
231 | #'
232 | #' @examples
233 | #' cmode(rpois(1000, 20))
234 | cmode <- function(x) {
235 | i <- as.integer(x)
236 | if (any(x - i != 0)) {
237 | warning("`x` not discrete. Converting vector with `as.integer`")
238 | x <- i
239 | }
240 | x <- sort(x)
241 | y <- rle(x)
242 | y$values[which.max(y$lengths)]
243 | }
244 |
245 | #' Trim extreme values at each end of a vector.
246 | #'
247 | #' @param x A [numeric] vector
248 | #' @param trim Proportion of vector length to trim. Must be between 0 and 1.
249 | #' E.g., a value 0.05 (default) trims 2.5\% off each end of a sorted vector.
250 | #' @param na.rm omit `NA` values. May result in different size vector.
251 | #'
252 | #' @return A [numeric] vector in the original order of `x`, but with trimmed
253 | #' values as `NA` if `na.rm=TRUE` or with these values removed if `FALSE`
254 | #' (which will result in a different sized vector from the input).
255 | #' @export
256 | #' @examples
257 | #' x <- rgamma(10000, 1, 1)
258 | #' range(x)
259 | #' length(x) # <- 10000
260 | #' sum(is.na(x)) # <- 0
261 | #'
262 | #' t <- trim_ends(x, trim = 0.1)
263 | #' range(t)
264 | #' length(t) # <- 9000
265 | #' sum(is.na(t)) # <- 0
266 | #'
267 | #' t <- trim_ends(x, 0.1, na.rm = FALSE)
268 | #' range(t, na.rm = TRUE)
269 | #' length(t) # <- 10000
270 | #' sum(is.na(t)) # <- 1000
271 | trim_ends <- function(x, trim=0.05, na.rm=TRUE) {
272 | if (!is.numeric(trim)) {
273 | stop("`trim` must be a numeric value.")
274 | }
275 |
276 | if (trim < 0 || trim > 1) {
277 | stop("trim amount must be between 0 and 1")
278 | }
279 |
280 | is_na <- is.na(x)
281 | len_finite <- sum(!is_na)
282 | len_trim <- as.integer(floor(len_finite * (trim / 2)))
283 |
284 | # attributes
285 | which_na <- which(is_na)
286 | which_trimmed <- integer()
287 | trim_size <- len_trim * 2L
288 |
289 | if (len_trim > 0L) {
290 | if (len_finite - trim_size < 1) {
291 | warning("trim amount results in zero length vector or all NAs")
292 | x[] <- NA
293 | } else {
294 | x_i_sort <- order(x, na.last=TRUE)
295 | trim_index <- seq_len(len_trim)
296 | trim_index <- unique(c(trim_index, len_finite - trim_index + 1))
297 | which_trimmed <- sort(x_i_sort[trim_index])
298 | x[which_trimmed] <- NA
299 | }
300 | }
301 |
302 | if (na.rm) {
303 | x <- x[!is.na(x)]
304 | }
305 |
306 | attr(x, "na.action") <- which_na
307 | attr(x, "trim.action") <- which_trimmed
308 | attr(x, "trim.size") <- trim_size
309 | x
310 | }
311 |
312 |
313 | # misc --------------------------------------------------------------------
314 |
315 |
316 | prop_in_range <- function(x, lower, upper) {
317 | sum(x > lower & x < upper) / length(x)
318 | }
319 |
320 | probit_tbl <- function(x, k) {
321 | pct <- ecdf(x)(x)
322 | brks <- range_sequence(c(0, 1), k + 1)
323 | idx <- cut(pct, breaks=brks, include.lowest=TRUE, right=FALSE, labels=FALSE)
324 | data.table(qmin=brks[idx], qmax=brks[idx + 1], ecdf=pct)
325 | }
326 |
327 | rgamma2 <- function(n, mean=1, sd=1) {
328 | rgamma(n, (mean / sd)^2, mean / sd^2)
329 | }
330 |
331 | rnbinom2 <- function(n, mean=1, sd=1, min_size=1) {
332 | size <- max(min_size, mean^2 / (sd^2 - mean))
333 | rnbinom(n, size=size, mu=mean)
334 | }
335 |
336 | csum_left <- function(x, init=0) {
337 | cs <- cumsum(c(init, x))
338 | na.omit(shift(cs, 1, NA, "lag"))
339 | }
340 |
341 | norm_vec <- function(x, na.rm=TRUE) {
342 | limits <- range_no_inf(x, na.rm=na.rm)
343 | (x - limits[1]) / diff(limits)
344 | }
345 |
346 | norm_vec_sum <- function(x, na.rm=TRUE) {
347 | x / sum(x, na.rm=na.rm)
348 | }
349 |
350 | range_no_inf <- function(x, na.rm=TRUE) {
351 | if (all_missing(x)) {
352 | return(c(NA, NA))
353 | }
354 |
355 | range(x, na.rm=na.rm)
356 | }
357 |
358 | logit <- function(p) {
359 | p[p < 0 | p > 1] <- NA
360 | log(p / (1 - p))
361 | }
362 |
363 | sigmoid <- function(x) {
364 | # more computationally stable form of: 1 / (1 + exp(-x))
365 | # also: logistic(x, l=1, k=1)
366 | exp(-log(1 + exp(-x)))
367 | }
368 |
369 | col_adj <- function(c, a) {
370 | v <- log(exp(c + 1) * sqrt(a)) - 1
371 | pmax(pmin(v, 1), 0)
372 | }
373 |
374 | # Snap a value to either the min or max if outside some range
375 | clip_range <- function(x, min=NULL, max=NULL) {
376 | if (!is.null(max)) {
377 | x <- pmin(x, max)
378 | }
379 | if (!is.null(min)) {
380 | x <- pmax(x, min)
381 | }
382 | return(x)
383 | }
384 |
--------------------------------------------------------------------------------
/R/theme.R:
--------------------------------------------------------------------------------
1 | .pt <- 72.27 / 25.4
2 | .stroke <- 96 / 25.4
3 |
4 |
5 | #' theme_mejr color mejr_palette
6 | #'
7 | #' @return list
8 | #' @export
9 | #'
10 | #' @examples
11 | #' mejr_palette()
12 | mejr_palette <- function() {
13 | list(
14 | black="#141214", gray="#939393", lightgray="#E8E8E8", yellow="#E0CF7C",
15 | magenta="#E069C6", cyan="#60ADAB", midline="#767698", fill="#8989B2",
16 | colour="#585872"
17 | )
18 | }
19 |
20 | #' Custom ggplot2 theme
21 | #'
22 | #' A complete, minimal theme to be used with the `ggplot2` package
23 | #'
24 | #' You can use `theme_update` to change some aspect of this theme after
25 | #' using `theme_set`.
26 | #'
27 | #' @inheritParams ggplot2::theme_gray
28 | #' @param black Values from 0 to 255, indicating the darkest line and
29 | #' text colors (255).
30 | #' @param margin_add additive adjustment of margin spacing and tick length (in "pt"
31 | #' units). May be positive or negative.
32 | #' @param debug Add debug info to text.
33 | #' @param FUN Call a function before returning the theme elements.
34 | #' @param ... Arguments passed to `FUN`
35 | #' @seealso [mejr_geom_defaults], [ggplot2::theme_update], [ggplot2::theme_set]
36 | #' @export
37 | #' @examples
38 | #' \donttest{
39 | #' library(ggplot2)
40 | #'
41 | #' theme_set(theme_mejr(debug = TRUE))
42 | #' example_plot()
43 | #'
44 | #' theme_set(theme_mejr())
45 | #' theme_update(axis.text = element_blank()) # any updates can go here
46 | #' example_plot()
47 | #' }
48 | theme_mejr <- function(base_size=11, base_family=getOption("ggdistribute.font"),
49 | black=67, margin_add=2, debug=FALSE, FUN=NULL, ...) {
50 | black <- gray2(black)
51 |
52 | if (is.null(margin_add) | scale_add(base_size, 1 / 7, margin_add) < 0) {
53 | margin_add <- 0
54 | }
55 |
56 | mejr_geom_defaults(base_size, black)
57 |
58 | if (!is.null(FUN)) {
59 | do.call(match.fun(FUN), list(...))
60 | }
61 |
62 | # make theme elements --------------------------------------------------------
63 |
64 | light_gray <- rgb(0, 0, 0, .05)
65 |
66 | theme(
67 | line=element_line(
68 | colour=black, size=scale_add(base_size, 1 / 36), linetype=1, lineend="butt"
69 | ),
70 | rect=element_rect(
71 | fill="transparent", colour=black,
72 | size=scale_add(base_size, 1 / 18), linetype=1
73 | ),
74 | text=element_text(
75 | family=base_family, face="plain", colour=black, size=base_size,
76 | hjust=0.5, vjust=0.5, angle=0, lineheight=1,
77 | margin=margin(
78 | t=scale_add(base_size, 0.45), r=scale_add(base_size, 0.45),
79 | b=scale_add(base_size, 0.45), l=scale_add(base_size, 0.45),
80 | unit="pt"
81 | ), debug=debug
82 | ),
83 | title=element_text(
84 | family=base_family, face="plain", colour=black,
85 | size=scale_add(base_size, 1.1), hjust=0, vjust=0.5, angle=0, lineheight=0.9,
86 | margin=margin(
87 | t=0, r=0, b=scale_add(base_size, 0.25, margin_add), l=0, unit="pt"
88 | ),
89 | debug=debug
90 | ),
91 | axis.line=element_line(),
92 | axis.line.x=NULL,
93 | axis.line.y=NULL,
94 | axis.ticks=element_line(),
95 | axis.ticks.x=element_line(),
96 | axis.ticks.y=element_line(),
97 | axis.ticks.length=grid::unit(clip_range(margin_add / 1.25, 1), "pt"),
98 | axis.text=element_text(size=rel(.75)),
99 | axis.text.x=element_text(
100 | hjust=0.5, vjust=1,
101 | margin=margin(
102 | t=scale_add(base_size, 0.25, margin_add),
103 | r=scale_add(base_size, 0.25, margin_add), b=scale_add(base_size, 0.125),
104 | l=scale_add(base_size, 0.25, margin_add), unit="pt"
105 | )
106 | ),
107 | axis.text.x.top=element_text(
108 | vjust=0, margin=margin(
109 | t=scale_add(base_size, 0.125),
110 | r=scale_add(base_size, 0.25, margin_add),
111 | b=scale_add(base_size, 0.25, margin_add),
112 | l=scale_add(base_size, 0.25, margin_add), unit="pt"
113 | )
114 | ),
115 | axis.text.y=element_text(hjust=1, margin=margin(
116 | t=scale_add(base_size, 0.25, margin_add),
117 | r=scale_add(base_size, 0.25, margin_add),
118 | b=scale_add(base_size, 0.25, margin_add),
119 | l=scale_add(base_size, 0.125), unit="pt"
120 | )),
121 | axis.text.y.right=element_text(
122 | hjust=0, margin=margin(
123 | t=scale_add(base_size, 0.25, margin_add),
124 | r=scale_add(base_size, 0.125),
125 | b=scale_add(base_size, 0.25, margin_add),
126 | l=scale_add(base_size, 0.25, margin_add), unit="pt"
127 | )
128 | ),
129 | axis.title=element_text(face="bold", size=rel(0.875)),
130 | axis.title.x=element_text(
131 | vjust=0.5, hjust=0.5,
132 | margin=margin(
133 | t=scale_add(base_size, 0.4, margin_add / 2), r=scale_add(base_size, 0),
134 | b=scale_add(base_size, 0), l=scale_add(base_size, 0), unit="pt"
135 | )
136 | ),
137 | axis.title.x.top=element_text(
138 | margin=margin(
139 | t=scale_add(base_size, 0), r=scale_add(base_size, 0),
140 | b=scale_add(base_size, 0.4, margin_add / 2),
141 | l=scale_add(base_size, 0), unit="pt"
142 | )
143 | ),
144 | axis.title.y=element_text(
145 | angle=90, vjust=0.5, hjust=0,
146 | margin=margin(
147 | t=scale_add(base_size, 0), r=scale_add(base_size, 0.4, margin_add / 2),
148 | b=scale_add(base_size, 0), l=scale_add(base_size, 0), unit="pt"
149 | )
150 | ),
151 | axis.title.y.right=element_text(
152 | hjust=1, vjust=0.5, angle=270,
153 | margin=margin(
154 | t=scale_add(base_size, 0), r=scale_add(base_size, 0),
155 | b=scale_add(base_size, 0),
156 | l=scale_add(base_size, 0.4, margin_add / 2), unit="pt"
157 | )
158 | ),
159 | legend.background=element_blank(),
160 | legend.key=element_blank(),
161 | legend.key.size=grid::unit(scale_add(base_size, 1.25), "pt"),
162 | legend.key.height=NULL,
163 | legend.key.width=NULL,
164 | legend.text=element_text(size=rel(0.5)),
165 | legend.text.align=0.5,
166 | legend.title=element_text(face="plain", size=rel(0.7)),
167 | legend.title.align=0.5,
168 | legend.position="bottom",
169 | legend.direction="horizontal",
170 | legend.justification="center",
171 | legend.box="horizontal",
172 | legend.box.just="center",
173 | legend.box.background=element_rect(
174 | colour=black, size=rel(0.25), fill="transparent"
175 | ),
176 | legend.box.margin=margin(
177 | t=scale_add(base_size, 0.125), r=scale_add(base_size, 0.125),
178 | b=scale_add(base_size, 0.125), l=scale_add(base_size, 0.125), unit="pt"
179 | ),
180 | legend.box.spacing=grid::unit(scale_add(base_size, 1 / 3, margin_add / 2), "pt"),
181 | legend.margin=margin(
182 | t=scale_add(base_size, 0.125), r=scale_add(base_size, 1 / 3),
183 | b=scale_add(base_size, 0.125), l=scale_add(base_size, 1 / 3), unit="pt"
184 | ),
185 | legend.spacing=grid::unit(scale_add(base_size, 0.125, margin_add), "pt"),
186 | legend.spacing.x=NULL,
187 | legend.spacing.y=NULL,
188 | panel.background=element_blank(),
189 | panel.border=element_rect(size=rel(0.9), colour=light_gray),
190 | panel.grid=element_blank(),
191 | panel.grid.major=element_blank(),
192 | panel.grid.minor=element_blank(),
193 | panel.grid.major.y=NULL,
194 | panel.grid.minor.y=NULL,
195 | panel.grid.major.x=NULL,
196 | panel.grid.minor.x=NULL,
197 | panel.ontop=FALSE,
198 | panel.spacing=grid::unit(scale_add(base_size, 0.25, margin_add), "pt"),
199 | panel.spacing.x=NULL,
200 | panel.spacing.y=NULL,
201 | strip.background=element_rect(colour=gray(.94), size=rel(0.5), fill=light_gray),
202 | strip.text=element_text(size=rel(0.7), face="bold"),
203 | strip.text.x=element_text(
204 | hjust=0.5, vjust=0.5,
205 | margin=margin(
206 | t=scale_add(base_size, 0.25), r=scale_add(base_size, 0.125),
207 | b=scale_add(base_size, 0.25), l=scale_add(base_size, 0.125), unit="pt"
208 | )
209 | ),
210 | strip.text.y=element_text(
211 | vjust=0.5, hjust=0.5, angle=270,
212 | margin=margin(
213 | t=scale_add(base_size, 0.125), r=scale_add(base_size, 0.25),
214 | b=scale_add(base_size, 0.125), l=scale_add(base_size, 0.25), unit="pt"
215 | )
216 | ),
217 | strip.placement="outside",
218 | strip.placement.x=NULL,
219 | strip.placement.y=NULL,
220 | strip.switch.pad.grid=grid::unit(scale_add(base_size, 0.25, margin_add), "pt"),
221 | strip.switch.pad.wrap=grid::unit(scale_add(base_size, 0.25, margin_add), "pt"),
222 | plot.background=element_blank(),
223 | plot.title=element_text(
224 | face="bold", hjust=0,
225 | margin=margin(
226 | t=scale_add(base_size, 0), r=scale_add(base_size, 0),
227 | b=scale_add(base_size, 1 / 3, margin_add / 1.5),
228 | l=scale_add(base_size, 0), unit="pt"
229 | )
230 | ),
231 | plot.tag=element_text(face="bold"),
232 | plot.tag.position="topleft",
233 | plot.subtitle=element_text(
234 | hjust=0, face="plain", size=rel(0.9),
235 | margin=margin(
236 | t=scale_add(base_size, 0), r=scale_add(base_size, 0),
237 | b=scale_add(base_size, 1 / 3, margin_add),
238 | l=scale_add(base_size, 0), unit="pt"
239 | )
240 | ),
241 | plot.caption=element_text(
242 | hjust=0.5, size=rel(0.75), face="italic",
243 | margin=margin(
244 | t=scale_add(base_size, 0.5, margin_add), r=scale_add(base_size, 0.75),
245 | b=scale_add(base_size, 0.125), l=scale_add(base_size, 0.75), unit="pt"
246 | )
247 | ),
248 | plot.margin=margin(
249 | t=scale_add(base_size, 1 / 7), r=scale_add(base_size, 1 / 7),
250 | b=scale_add(base_size, 1 / 7), l=scale_add(base_size, 1 / 7), unit="pt"
251 | ),
252 | complete=TRUE
253 | )
254 | }
255 |
256 | #' Setup defaults for specific geoms
257 | #'
258 | #' @inheritParams theme_mejr
259 | #' @param gray gray color value (0-255)
260 | #' @param lty linetype
261 | #' @param lwd linewidth
262 | #' @param cex point size
263 | #' @param stroke stroke width
264 | #' @param alpha alpha
265 | #' @param pch point shape
266 | #' @param txt text size
267 | #' @param reset reset all back to default
268 | #'
269 | #' @return NULL
270 | #' @export
271 | #'
272 | #' @examples
273 | #' # This will change the point size and shape for
274 | #' # all geoms in which GeomPoint inherits from.
275 | #' mejr_geom_defaults(cex = 1.1, pch = 19)
276 | #'
277 | #' # Reset defaults back to their original state.
278 | #' mejr_geom_defaults(reset=TRUE)
279 | mejr_geom_defaults <- function(base_size=11, black=51, gray=214, lty=3, lwd=base_size /
280 | 20,
281 | cex=base_size / 9, stroke=base_size * .05, alpha=0.5,
282 | pch=21, txt=base_size / 4, reset=FALSE) {
283 | gray <- gray2(gray)
284 | black <- gray2(black)
285 |
286 | updates <- list(
287 | text=list(geoms="text", opts=list(size=txt, colour=black)),
288 | lines=list(geoms=c(
289 | "line", "hline", "vline", "linerange", "errorbar",
290 | "errorbarh"
291 | ), opts=list(size=lwd, colour=black)),
292 | ablines=list(
293 | geoms=c("hline", "vline", "abline"),
294 | opts=list(size=lwd, colour=gray, linetype=lty)
295 | ),
296 | bar=list(geoms="bar", opts=list(size=lwd, colour=NA)),
297 | smooth=list(geoms="smooth", opts=list(
298 | size=lwd, colour=black, fill=gray
299 | )),
300 | point=list(geoms="point", opts=list(
301 | size=cex, colour=black, shape=pch,
302 | stroke=stroke, fill=NA, alpha=alpha
303 | ))
304 | )
305 |
306 | gg_defaults <- getOption("ggdistribute.geom.defaults")
307 | gg_edited <- getOption("ggdistribute.geom.edits")
308 |
309 | on.exit({
310 | options(ggdistribute.geom.defaults=gg_defaults)
311 | options(ggdistribute.geom.edits=gg_edited)
312 | })
313 |
314 | for (u in seq_along(updates)) {
315 | geoms <- updates[[u]]$geoms
316 | changes <- updates[[u]]$opts
317 |
318 | for (g in geoms) {
319 | if (length(gg_defaults[[g]]) < 1) {
320 | gg_defaults[[g]] <- geom_defaults(g)
321 | }
322 | if (reset) {
323 | update_geom_defaults(g, gg_defaults[[g]])
324 | } else {
325 | gg_defaults$edited <- TRUE
326 | gg_edited[[g]] <- changes
327 | update_geom_defaults(g, changes)
328 | }
329 | }
330 | }
331 |
332 | invisible()
333 | }
334 |
335 |
336 | geom_defaults <- function(geom) {
337 | if (is.character(geom)) {
338 | g <- find_subclass("Geom", geom, parent.frame())
339 | } else {
340 | if (inherits(geom, "Geom")) {
341 | g <- geom
342 | } else {
343 | stop("`geom` must be a string (like \"point\")",
344 | " or a Geom object (like GeomPoint).",
345 | call.=FALSE)
346 | }
347 | }
348 | unclass(g$default_aes)
349 | }
350 |
351 |
352 | #' Test theme by printing plots to pdf and viewport
353 | #'
354 | #' @param w pdf width (inches)
355 | #' @param h pdf height (inches)
356 | #' @param eplot list of options for `example_plot`
357 | #' @param mejr list of options for `theme_mejr(...)`
358 | #' @param gg further theme customization with ggplot::theme(...)
359 | #' @param print show the `eplot` plot
360 | #' @param with_test_theme also print the same plot using `ggplot2::theme_test`
361 | #' @param dir directory where to save temp pdf files, such as tempdir()
362 | #' @return NULL
363 | test_mejr_theme <- function(w=6.875, h=4.5, eplot=list(), mejr=list(), gg=theme(),
364 | print=TRUE, with_test_theme=FALSE, dir) {
365 | if (length(eplot) < 1) {
366 | eplot <- list()
367 | }
368 |
369 | if (length(mejr) < 1) {
370 | mejr <- list()
371 | }
372 |
373 | cat(dir)
374 |
375 | if (with_test_theme) {
376 | test_theme_args <- list(base_size=11, debug=FALSE)
377 | test_theme_args <- modifyList(
378 | test_theme_args, Filter(Negate(is.null), mejr[c("base_size", "debug")]),
379 | keep.null=TRUE
380 | )
381 |
382 | mejr_geom_defaults(reset=TRUE)
383 | theme_set(do.call("theme_test", list()))
384 |
385 | ggsave(
386 | filename=normalizePath(file.path(dir, "theme_test.pdf"), mustWork=F),
387 | example_plot() + do.call("theme_test", test_theme_args) + gg, width=w,
388 | height=h, device="pdf"
389 | )
390 | }
391 |
392 | theme_set(theme_mejr())
393 |
394 | p_mejr1 <- example_plot() + do.call(theme_mejr, mejr) + gg
395 | p_mejr2 <- do.call(example_plot, eplot) + do.call(theme_mejr, mejr) + gg
396 |
397 | ggsave(
398 | filename=normalizePath(file.path(dir, "theme_mejr1.pdf"), mustWork=FALSE),
399 | p_mejr1, width=w, height=h, device="pdf"
400 | )
401 |
402 | ggsave(
403 | filename=normalizePath(file.path(dir, "theme_mejr2.pdf"), mustWork=FALSE),
404 | p_mejr2, width=w, height=h, device="pdf"
405 | )
406 |
407 | if (print) {
408 | grid::grid.draw(p_mejr2)
409 | }
410 |
411 | invisible()
412 | }
413 |
414 |
415 | #' Write text to one of four corners of a plot
416 | #'
417 | #' @details If multiple panels, will write to all panels.
418 | #'
419 | #' @param text character string
420 | #' @param pos character of `"tl"`, `"tr"`, `"bl"`, `"br"` to
421 | #' indicate position (you may also use the full names, `"bottomleft"`, etc...)
422 | #' @param ... additional options passed to [ggplot2::geom_label]
423 | #' @param geom "text" or "label" geoms
424 | #'
425 | #' @return ggplot layer
426 | #' @export
427 | #'
428 | #' @examples
429 | #' posterior_plot() + annotate_corner("Hi.", "bottomright")
430 | annotate_corner <- function(text, pos="tl", geom=c("text", "label"), ...) {
431 | x <- -Inf
432 | y <- Inf
433 | h <- 0
434 | v <- 1
435 |
436 | switch(tolower(pos), topleft= , tl={
437 | x <- -Inf
438 | y <- Inf
439 | h <- 0
440 | v <- 1
441 | }, topright= , tr={
442 | x <- Inf
443 | y <- Inf
444 | h <- 1
445 | v <- 1
446 | }, bottomleft= , bl={
447 | x <- -Inf
448 | y <- -Inf
449 | h <- 0
450 | v <- 0
451 | }, bottomright= ,
452 | br={
453 | x <- Inf
454 | y <- -Inf
455 | h <- 1
456 | v <- 0
457 | }, stop("incorrect position"))
458 |
459 | annotate(match.arg(geom), x, y, label=text, hjust=h, vjust=v, ...)
460 | }
461 |
462 |
463 | #' Add labels to existing plot
464 | #'
465 | #' Uses a normalized coordinate system to add text anywhere on the current plot.
466 | #'
467 | #' @param labels character vector of labels to use
468 | #' @param x horz positions of items in `labels`
469 | #' @param y vert positions of items in `labels`
470 | #' @param g list of options passed to [grid::gpar]
471 | #' @param ... optional args passed to [grid::grid.text]
472 | #'
473 | #' @return NULL. prints to current graphics device.
474 | #' @export
475 | #' @seealso [grid::grid.text], [grid::gpar]
476 | #' @examples
477 | #' example_plot()
478 | #' label_plot(c('a label', 'another one'), c(.1, .9), c(.95, .1))
479 | #'
480 | #' # use extra options from grid::grid.text
481 | #' label_plot('last one', 0.5, 0.5, just='center')
482 | label_plot <- function(labels, x, y, g=list(fontsize=14, fontface="bold"), ...) {
483 | l <- length(labels)
484 | if (!all(unlist(lapply(list(labels, x, y), length)) == l)) {
485 | stop("make sure length of labels, x, y are equal")
486 | }
487 | for (i in seq_len(l)) {
488 | grid::grid.text(
489 | label=labels[i], x=unit(x[i], "npc"), y=unit(y[i], "npc"),
490 | gp=do.call(grid::gpar, g), ...
491 | )
492 | }
493 | }
494 |
--------------------------------------------------------------------------------
/R/zzz.R:
--------------------------------------------------------------------------------
1 | set_pkg_opts <- function(..., opt_list=NULL) {
2 | pkg_opts <- c(pairlist(...), as.pairlist(opt_list))
3 |
4 | if (is.null(pkg_opts)) {
5 | return(invisible())
6 | }
7 |
8 | opts <- names(options())
9 | pkg_opt_names <- names(pkg_opts)
10 | new_opts <- nzchar(pkg_opt_names) & !pkg_opt_names %in% opts
11 |
12 | if (any(new_opts)) {
13 | options(pkg_opts[pkg_opt_names[new_opts]])
14 | } else {
15 | invisible()
16 | }
17 | }
18 |
19 | .onLoad <- function(libname, pkgname) {
20 | set_pkg_opts(
21 | ggdistribute.font="sans", ggdistribute.geom.defaults=list(edited=FALSE),
22 | ggdistribute.geom.edits=list()
23 | )
24 | invisible()
25 | }
26 |
27 | .onAttach <- function(libname, pkgname) {
28 | packageStartupMessage("ggdistribute loaded")
29 | }
30 |
--------------------------------------------------------------------------------
/README.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | output: github_document
3 | ---
4 |
5 |
6 |
7 | ```{r, echo = FALSE}
8 | knitr::opts_chunk$set(
9 | collapse=TRUE,
10 | comment="#>",
11 | strip.white=FALSE,
12 | tidy=FALSE,
13 | dpi=300,
14 | fig.align="center",
15 | fig.path="man/figures/README-",
16 | fig.width=5.25,
17 | fig.height=3.8,
18 | out.width="700px"
19 | )
20 | ```
21 |
22 |
23 | [](https://cran.r-project.org/package=ggdistribute)
24 |
25 | # ggdistribute
26 |
27 | A `ggplot2` Extension for Plotting Unimodal Distributions
28 |
29 | The `ggdistribute` package is an extension for plotting posterior or other types of unimodal distributions that require overlaying information about a distribution's intervals. It makes use of the `ggproto` system to extend `ggplot2`, providing additional "geoms", "stats", and "positions." The extensions integrate with existing `ggplot2` layer elements.
30 |
31 | ## Example
32 |
33 | ```{r, echo=FALSE, message=FALSE, results='hide', warning=FALSE}
34 | library(ggplot2)
35 | devtools::load_all(".", export_all = FALSE)
36 | theme_set(theme_mejr())
37 | ```
38 |
39 | The package function `example_plot()` is an overview of combining `ggdistribute` with other `ggplot2` elements. The contents of this function are printed below and gives details about the extended parts to `ggplot2`.
40 |
41 | ```{r, eval=FALSE}
42 | library(ggplot2)
43 | library(ggdistribute)
44 | ```
45 |
46 | ```{r turtle_snails, echo = FALSE, fig.width=5, fig.height=3, out.width="100%"}
47 | plot(example_plot())
48 | ```
49 |
50 | ```{r prin_ex_plot, echo=FALSE, results='asis'}
51 | ggdistribute:::function2chunk("example_plot")
52 | ```
53 |
54 | ## Additional examples from an arbritrary dataset
55 |
56 | ```{r}
57 | # total number of samples in the dataset
58 | N <- 2500
59 | means <- c(-1, 2, 3, 5)
60 | ```
61 |
62 | The `data` object below is a randomly generated dataset of `r length(means)` different normal distributions. Two factors, `Condition` and `Group`, are assigned to subsets of the generated values. `r N` samples are generated for each value of `mu` for a total of $ `r N*length(means)` $ rows.
63 |
64 | ```{r norm_data}
65 | data <- data_normal_sample(mu = means, n = N)
66 | ```
67 |
68 | Create a new grouping variable called `Level` based on the column `Group`.
69 |
70 | ```{r norm_data_grps}
71 | # number of levels to make
72 | num_levels <- 8L
73 |
74 | # R version >= 3.5 now let's you assign factors this way.
75 | data$Level <- with(data, factor(
76 | Group,
77 | levels = letters[seq_len(num_levels)],
78 | labels = c(rep("Low", 3), rep("Mid", 2), rep("High", 3)),
79 | ordered = TRUE
80 | ))
81 | ```
82 |
83 | Show unique groups per `Group`, `Condition`, and `Level` to help understand the data factors.
84 |
85 | ```{r}
86 | unique(data[, c("Group", "Condition", "Level")])
87 | ```
88 |
89 | ### Facetting and spreading groups
90 |
91 | ```{r space_ships, fig.width=5, fig.height=4}
92 | ggplot(data) +
93 | aes(x=value, y=Condition, group=Group) +
94 | geom_posterior(
95 | aes(fill=Level),
96 | mirror=TRUE,
97 | show.legend=FALSE,
98 | adjust=1.5,
99 | brighten=c(6, 0, 2.5),
100 | position=position_spread(reverse=TRUE)
101 | ) +
102 | geom_point(
103 | aes(color=Level, shape=Condition),
104 | alpha=.08,
105 | fill=NA,
106 | show.legend=FALSE,
107 | position=position_jitter(0, .45)
108 | ) +
109 | coord_cartesian(ylim=c(0.5, 2.5), expand=FALSE) +
110 | facet_wrap(~ Level, scales="free") +
111 | labs(title="Space Invaders", y="Condition", x="Parameter estimate")
112 | ```
113 |
114 | ### Changing the appearance of `geom_posterior`
115 |
116 | ```{r candy_wrappers, fig.width=5, fig.height=4}
117 | ggplot(data) +
118 | aes(x=value, y=Group) +
119 | geom_vline(
120 | xintercept=0, size=.6
121 | ) +
122 | geom_posterior(
123 | aes(color=Condition),
124 | midline=NULL,
125 | mirror=TRUE,
126 | fill="#FFFFFF",
127 | draw_sd=FALSE,
128 | interval_type="hdi",
129 | vjust=0,
130 | position=position_spread(height=2)
131 | ) +
132 | labs(
133 | title="Candy Wrappers",
134 | x="Parameter estimate",
135 | y="Sample location"
136 | ) +
137 | scale_x_continuous(breaks=seq(-10, 10, 1)) +
138 | theme(
139 | legend.position=c(.025, .9),
140 | legend.justification=c(0, 0),
141 | panel.grid.major.y=element_line(color=gray(.92))
142 | )
143 | ```
144 |
145 | ### The *y* axis is a repeated, continuous grouping variable
146 |
147 | The variable `GroupScore` is a continuous variable assigned to each `Group`. The distributions will be positioned at the start of the y value for each group, and resized to not overlap with the next group. Resizing can be overriden by specifying `height` in `position_spread`.
148 |
149 | ```{r y_cont}
150 | unique(data[, c("Group", "GroupScore")])
151 | ```
152 |
153 | ```{r rainbow_hills, fig.width=5, fig.height=6}
154 | ggplot(data) +
155 | aes(x=value, y=GroupScore) +
156 | geom_vline(
157 | xintercept=0, size=.6
158 | ) +
159 | geom_posterior(
160 | aes(fill=Group),
161 | midline="#FFFFFF",
162 | colour="#FFFFFF",
163 | alpha=0.7,
164 | brighten=c(1.3, 0, -1.3),
165 | interval_type="hdi",
166 | position=position_spread(height=0.5, padding=0)
167 | ) +
168 | labs(
169 | title="Rainbow Hills",
170 | x="Parameter estimate",
171 | y="Group's score"
172 | ) +
173 | scale_x_continuous(breaks=seq(-10, 10, 1)) +
174 | scale_y_continuous(breaks=seq(-10, 10, .5))
175 | ```
176 |
177 | ## How to install
178 |
179 | ### Dependencies
180 |
181 | - R:
182 |
183 | A current R installation.
184 |
185 | #### Dependencies for installing the development version of this package
186 |
187 | - `devtools` package:
188 |
189 | The `devtools` package is an R package that makes it easier to install local or remote content as an R package that can be used like any other standard R package. You can install `devtools` by opening up RStudio or an R terminal and running
190 |
191 | ```{r devtools-inst, eval=FALSE}
192 | install.packages("devtools")
193 | ```
194 |
195 | For Windows users, you *may* be required to install Rtools first before you can use the `devtools` package, if there is any code that needs to be compiled. These are a set of build tools customized for building R packages (see the `devtools` link above for more details).
196 |
197 | - Build tools:
198 |
199 | ### Installing from CRAN
200 |
201 |
202 | If you want to use the last version that was uploaded to the CRAN repository, do the following:
203 |
204 | ```{r cran-inst, eval=FALSE}
205 | install.packages("ggdistribute")
206 | ```
207 |
208 | ### Installing from the downloaded package content folder
209 |
210 | If you have all of the `ggdistribute` package contents (e.g., an unzipped folder containing `DESCRIPTION`, `NAMESPACE`, `R/`, etc...), you can open up the `ggdistribute.Rproj` file in RStudio and use both `devtools` and RStudio to load or install package.
211 |
212 | The first step is to make sure you have all the package dependencies (other packages that this pacakge relies on) to be able to load or install the `ggdistribute` package materials. You can run the line below to install dependencies first.
213 |
214 | ```{r local-inst-dep, eval=FALSE}
215 | devtools::install_dev_deps()
216 | ```
217 |
218 | After the dependencies are installed, you can now build and install `ggdistribute` from the current working directory.
219 | Assuming the `ggdistribute` project is loaded in RStudio, you can leave out the first argument.
220 |
221 | ```{r local-inst, eval=FALSE}
222 | devtools::install()
223 | ```
224 |
225 | If installing from a different working directory, enter the path of the package contents to manually specify what to install.
226 |
227 | ```{r local-inst-alt, eval=FALSE}
228 | devtools::install_dev_deps("/Path/to/the/folder/ggdistribute")
229 | devtools::install("/Path/to/the/folder/ggdistribute")
230 | ```
231 |
232 |
233 | ### Installing from GitHub
234 |
235 | If `devtools` are installed, you may use the `install_github()` function to download and install the development version of the package from this GitHub repository instead of the one hosted on CRAN. Run the code below to download and install the development version:
236 |
237 | ```{r gh-installation, eval = FALSE}
238 | devtools::install_github("iamamutt/ggdistribute")
239 | ```
240 |
241 | or to install all suggested packages as well...
242 |
243 | ```{r gh-installation-dep, eval = FALSE}
244 | devtools::install_github("iamamutt/ggdistribute", dependencies=TRUE)
245 | ```
246 |
247 | ### Loading the package
248 |
249 | If successful, the package should now be installed and can be loaded as any other package. Repeat the last intall step if there are updates to the package, or complete all steps to install on another machine. You should now be able to use the package materials and should see it in your packages tab if using RStudio. It should be loaded like any other package.
250 |
251 | ```{r load-pkg, eval=FALSE}
252 | library(ggdistribute)
253 | ```
254 |
255 |
256 | ## Getting help
257 |
258 | ### Browsing the vignettes
259 |
260 | Vignettes can be viewed in several different ways.
261 |
262 | - pre-built and saved in the `inst\doc` folder on GitHub.
263 | - calling `vignette("geom_posterior", "ggdistribute")` from within R after the package is installed.
264 | - navigating to packages tab > ggdistribute > User guides, package vignettes... in RStudio.
265 |
266 | ### Viewing the help documentation
267 |
268 | View the package welcome page to navigate to different types of help documents
269 |
270 | ```{r show-welcome, eval=FALSE}
271 | package?ggdistribute
272 | ```
273 |
274 | Viewing package information and a list of exported objects:
275 |
276 | ```{r show-help, eval=FALSE}
277 | help(package = "ggdistribute")
278 |
279 | # or
280 | library(help="ggdistribute")
281 | ```
282 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | [](https://cran.r-project.org/package=ggdistribute)
5 |
6 | # ggdistribute
7 |
8 | A `ggplot2` Extension for Plotting Unimodal Distributions
9 |
10 | The `ggdistribute` package is an extension for plotting posterior or
11 | other types of unimodal distributions that require overlaying
12 | information about a distribution’s intervals. It makes use of the
13 | `ggproto` system to extend `ggplot2`, providing additional “geoms”,
14 | “stats”, and “positions.” The extensions integrate with existing
15 | `ggplot2` layer elements.
16 |
17 | ## Example
18 |
19 | The package function `example_plot()` is an overview of combining
20 | `ggdistribute` with other `ggplot2` elements. The contents of this
21 | function are printed below and gives details about the extended parts to
22 | `ggplot2`.
23 |
24 | ``` r
25 | library(ggplot2)
26 | library(ggdistribute)
27 | ```
28 |
29 |
30 |
31 | ``` r
32 | example_plot <-
33 | function() {
34 | # color palette
35 | colors <- mejr_palette()
36 |
37 | ggplot(sre_data(5000), aes_string(y="effect")) +
38 |
39 | # ggdistribute specific elements -------------------------------------------
40 | geom_posterior(
41 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42 | # geom_posterior() aesthetics mappings
43 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
44 | aes_string(x="value", fill="contrast"),
45 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
46 | # options passed to stat_density_ci() for estimating intervals
47 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
48 | interp_thresh=.001, # threshold for interpolating segment gaps
49 | center_stat="median", # measure of central tendency
50 | ci_width=0.90, # width corresponding to CI segments
51 | interval_type="ci", # quantile intervals not highest density interval
52 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
53 | # options passed to stat_density_ci() for estimating density
54 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
55 | bw=".nrd0", # bandwidth estimator type
56 | adjust=1.5, # adjustment to bandwidth
57 | n=1024, # number of samples in final density
58 | trim=.005, # trim `x` this proportion before estimating density
59 | cut=1.5, # tail extension for zero density estimation
60 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61 | # geom_posterior() options
62 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
63 | draw_ci=TRUE, # toggle showing confidence interval parts
64 | draw_sd=TRUE, # toggle showing standard deviation parts
65 | mirror=FALSE, # toggle horizontal violin distributions
66 | midline=NULL, # line displaying center of dist. (NULL=aes color)
67 | brighten=c(3, 0, 1.333), # additive adjustment of segment fill colors
68 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
69 | # position_spread() options
70 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71 | position=position_spread(
72 | reverse=TRUE, # order of spreaded groups within panels
73 | padding=0.3, # shrink heights of distributions
74 | height="panel" # scale by heights within panels
75 | ), #
76 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
77 | # standard ggplot layer options
78 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79 | size=0.15, color=colors$gray, vjust=0.7, show.legend=FALSE
80 | ) +
81 |
82 | # standard ggplot2 elements ------------------------------------------------
83 | geom_vline(alpha=0.5, color=colors$gray, size=0.333, linetype=1, xintercept=0) +
84 | scale_x_continuous(breaks=seq(-1, 1, .05)) +
85 | facet_grid("contrast ~ .", scales="free_y", space="free_y") +
86 | scale_fill_manual(values=c(colors$yellow, colors$magenta, colors$cyan)) +
87 | labs(x="Difference in accuracy (posterior predictions)") +
88 | theme(
89 | legend.position="none", strip.text.y=element_text(angle=0, hjust=0.5),
90 | panel.border=element_rect(fill=NA, color=colors$lightgray, size=0.67),
91 | panel.grid=element_blank(), panel.ontop=FALSE, axis.title.y=element_blank(),
92 | plot.margin=margin(t=2, r=4, b=2, l=2, unit="pt")
93 | )
94 | }
95 | ```
96 |
97 | ## Additional examples from an arbritrary dataset
98 |
99 | ``` r
100 | # total number of samples in the dataset
101 | N <- 2500
102 | means <- c(-1, 2, 3, 5)
103 | ```
104 |
105 | The `data` object below is a randomly generated dataset of 4 different
106 | normal distributions. Two factors, `Condition` and `Group`, are assigned
107 | to subsets of the generated values. 2500 samples are generated for each
108 | value of `mu` for a total of $ 10^{4} $ rows.
109 |
110 | ``` r
111 | data <- data_normal_sample(mu = means, n = N)
112 | ```
113 |
114 | Create a new grouping variable called `Level` based on the column
115 | `Group`.
116 |
117 | ``` r
118 | # number of levels to make
119 | num_levels <- 8L
120 |
121 | # R version >= 3.5 now let's you assign factors this way.
122 | data$Level <- with(data, factor(
123 | Group,
124 | levels = letters[seq_len(num_levels)],
125 | labels = c(rep("Low", 3), rep("Mid", 2), rep("High", 3)),
126 | ordered = TRUE
127 | ))
128 | ```
129 |
130 | Show unique groups per `Group`, `Condition`, and `Level` to help
131 | understand the data factors.
132 |
133 | ``` r
134 | unique(data[, c("Group", "Condition", "Level")])
135 | #> # A tibble: 8 x 3
136 | #> Group Condition Level
137 | #>
138 | #> 1 a A Low
139 | #> 2 b A Low
140 | #> 3 c B Low
141 | #> 4 d B Mid
142 | #> 5 e C Mid
143 | #> 6 f C High
144 | #> 7 g D High
145 | #> 8 h D High
146 | ```
147 |
148 | ### Facetting and spreading groups
149 |
150 | ``` r
151 | ggplot(data) +
152 | aes(x=value, y=Condition, group=Group) +
153 | geom_posterior(
154 | aes(fill=Level),
155 | mirror=TRUE,
156 | show.legend=FALSE,
157 | adjust=1.5,
158 | brighten=c(6, 0, 2.5),
159 | position=position_spread(reverse=TRUE)
160 | ) +
161 | geom_point(
162 | aes(color=Level, shape=Condition),
163 | alpha=.08,
164 | fill=NA,
165 | show.legend=FALSE,
166 | position=position_jitter(0, .45)
167 | ) +
168 | coord_cartesian(ylim=c(0.5, 2.5), expand=FALSE) +
169 | facet_wrap(~ Level, scales="free") +
170 | labs(title="Space Invaders", y="Condition", x="Parameter estimate")
171 | ```
172 |
173 |
174 |
175 | ### Changing the appearance of `geom_posterior`
176 |
177 | ``` r
178 | ggplot(data) +
179 | aes(x=value, y=Group) +
180 | geom_vline(
181 | xintercept=0, size=.6
182 | ) +
183 | geom_posterior(
184 | aes(color=Condition),
185 | midline=NULL,
186 | mirror=TRUE,
187 | fill="#FFFFFF",
188 | draw_sd=FALSE,
189 | interval_type="hdi",
190 | vjust=0,
191 | position=position_spread(height=2)
192 | ) +
193 | labs(
194 | title="Candy Wrappers",
195 | x="Parameter estimate",
196 | y="Sample location"
197 | ) +
198 | scale_x_continuous(breaks=seq(-10, 10, 1)) +
199 | theme(
200 | legend.position=c(.025, .9),
201 | legend.justification=c(0, 0),
202 | panel.grid.major.y=element_line(color=gray(.92))
203 | )
204 | ```
205 |
206 |
207 |
208 | ### The *y* axis is a repeated, continuous grouping variable
209 |
210 | The variable `GroupScore` is a continuous variable assigned to each
211 | `Group`. The distributions will be positioned at the start of the y
212 | value for each group, and resized to not overlap with the next group.
213 | Resizing can be overriden by specifying `height` in `position_spread`.
214 |
215 | ``` r
216 | unique(data[, c("Group", "GroupScore")])
217 | #> # A tibble: 8 x 2
218 | #> Group GroupScore
219 | #>
220 | #> 1 a -0.885
221 | #> 2 b -0.839
222 | #> 3 c 2.18
223 | #> 4 d 2.33
224 | #> 5 e 2.81
225 | #> 6 f 3.07
226 | #> 7 g 4.90
227 | #> 8 h 4.93
228 | ```
229 |
230 | ``` r
231 | ggplot(data) +
232 | aes(x=value, y=GroupScore) +
233 | geom_vline(
234 | xintercept=0, size=.6
235 | ) +
236 | geom_posterior(
237 | aes(fill=Group),
238 | midline="#FFFFFF",
239 | colour="#FFFFFF",
240 | alpha=0.7,
241 | brighten=c(1.3, 0, -1.3),
242 | interval_type="hdi",
243 | position=position_spread(height=0.5, padding=0)
244 | ) +
245 | labs(
246 | title="Rainbow Hills",
247 | x="Parameter estimate",
248 | y="Group's score"
249 | ) +
250 | scale_x_continuous(breaks=seq(-10, 10, 1)) +
251 | scale_y_continuous(breaks=seq(-10, 10, .5))
252 | ```
253 |
254 |
255 |
256 | ## How to install
257 |
258 | ### Dependencies
259 |
260 | - R:
261 |
262 | A current R installation.
263 |
264 | #### Dependencies for installing the development version of this package
265 |
266 | - `devtools` package:
267 |
268 |
269 | The `devtools` package is an R package that makes it easier to install
270 | local or remote content as an R package that can be used like any other
271 | standard R package. You can install `devtools` by opening up RStudio or
272 | an R terminal and running
273 |
274 | ``` r
275 | install.packages("devtools")
276 | ```
277 |
278 | For Windows users, you *may* be required to install Rtools first before
279 | you can use the `devtools` package, if there is any code that needs to
280 | be compiled. These are a set of build tools customized for building R
281 | packages (see the `devtools` link above for more details).
282 |
283 | - Build tools:
284 |
285 | ### Installing from CRAN
286 |
287 | If you want to use the last version that was uploaded to the CRAN
288 | repository, do the following:
289 |
290 | ``` r
291 | install.packages("ggdistribute")
292 | ```
293 |
294 | ### Installing from the downloaded package content folder
295 |
296 | If you have all of the `ggdistribute` package contents (e.g., an
297 | unzipped folder containing `DESCRIPTION`, `NAMESPACE`, `R/`, etc…), you
298 | can open up the `ggdistribute.Rproj` file in RStudio and use both
299 | `devtools` and RStudio to load or install package.
300 |
301 | The first step is to make sure you have all the package dependencies
302 | (other packages that this pacakge relies on) to be able to load or
303 | install the `ggdistribute` package materials. You can run the line below
304 | to install dependencies first.
305 |
306 | ``` r
307 | devtools::install_dev_deps()
308 | ```
309 |
310 | After the dependencies are installed, you can now build and install
311 | `ggdistribute` from the current working directory. Assuming the
312 | `ggdistribute` project is loaded in RStudio, you can leave out the first
313 | argument.
314 |
315 | ``` r
316 | devtools::install()
317 | ```
318 |
319 | If installing from a different working directory, enter the path of the
320 | package contents to manually specify what to install.
321 |
322 | ``` r
323 | devtools::install_dev_deps("/Path/to/the/folder/ggdistribute")
324 | devtools::install("/Path/to/the/folder/ggdistribute")
325 | ```
326 |
327 | ### Installing from GitHub
328 |
329 | If `devtools` are installed, you may use the `install_github()` function
330 | to download and install the development version of the package from this
331 | GitHub repository instead of the one hosted on CRAN. Run the code below
332 | to download and install the development version:
333 |
334 | ``` r
335 | devtools::install_github("iamamutt/ggdistribute")
336 | ```
337 |
338 | or to install all suggested packages as well…
339 |
340 | ``` r
341 | devtools::install_github("iamamutt/ggdistribute", dependencies=TRUE)
342 | ```
343 |
344 | ### Loading the package
345 |
346 | If successful, the package should now be installed and can be loaded as
347 | any other package. Repeat the last intall step if there are updates to
348 | the package, or complete all steps to install on another machine. You
349 | should now be able to use the package materials and should see it in
350 | your packages tab if using RStudio. It should be loaded like any other
351 | package.
352 |
353 | ``` r
354 | library(ggdistribute)
355 | ```
356 |
357 | ## Getting help
358 |
359 | ### Browsing the vignettes
360 |
361 | Vignettes can be viewed in several different ways.
362 |
363 | - pre-built and saved in the `inst\doc` folder on GitHub.
364 | - calling `vignette("geom_posterior", "ggdistribute")` from within R
365 | after the package is installed.
366 | - navigating to packages tab \> ggdistribute \> User guides, package
367 | vignettes… in RStudio.
368 |
369 | ### Viewing the help documentation
370 |
371 | View the package welcome page to navigate to different types of help
372 | documents
373 |
374 | ``` r
375 | package?ggdistribute
376 | ```
377 |
378 | Viewing package information and a list of exported objects:
379 |
380 | ``` r
381 | help(package = "ggdistribute")
382 |
383 | # or
384 | library(help="ggdistribute")
385 | ```
386 |
--------------------------------------------------------------------------------
/cran-comments.md:
--------------------------------------------------------------------------------
1 | ## Test environments
2 |
3 | * local OS X install, R 3.5.1
4 | * ubuntu 12.04 (on travis-ci), R 3.5.1
5 | * win-builder (devel and release)
6 |
7 | ## R CMD check results
8 |
9 | 0 errors | 0 warnings | 0 note
10 |
11 | ## Reverse dependencies
12 |
13 | There are no reverse dependencies.
14 |
15 | ---
16 |
--------------------------------------------------------------------------------
/data/sre.rda:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iamamutt/ggdistribute/3efffa1ebfe20b6d7adf675412a7833b9feb8c04/data/sre.rda
--------------------------------------------------------------------------------
/ggdistribute.Rproj:
--------------------------------------------------------------------------------
1 | Version: 1.0
2 |
3 | RestoreWorkspace: No
4 | SaveWorkspace: No
5 | AlwaysSaveHistory: No
6 |
7 | EnableCodeIndexing: Yes
8 | UseSpacesForTab: Yes
9 | NumSpacesForTab: 2
10 | Encoding: UTF-8
11 |
12 | RnwWeave: knitr
13 | LaTeX: pdfLaTeX
14 |
15 | AutoAppendNewline: Yes
16 | StripTrailingWhitespace: Yes
17 | LineEndingConversion: Posix
18 |
19 | BuildType: Package
20 | PackageUseDevtools: Yes
21 | PackageInstallArgs: --no-multiarch --with-keep.source
22 | PackageCheckArgs: --run-donttest
23 | PackageRoxygenize: rd,collate,namespace
24 |
25 | QuitChildProcessesOnExit: Yes
26 |
--------------------------------------------------------------------------------
/inst/CITATION:
--------------------------------------------------------------------------------
1 | citHeader("To cite ggdistribute in publications use:")
2 |
3 | citEntry(entry = "Misc",
4 | title = "{ggdistribute}: {A ggplot2} Extension for Plotting Unimodal Distributions",
5 | author = person("Joseph M.", "Burling"),
6 | note = "R package version 1.0.1",
7 | year = "2018",
8 | url = "https://github.com/iamamutt/ggdistribute",
9 |
10 | textVersion =
11 | paste("Burling, Joseph M. (2018).",
12 | title = "ggdistribute: A ggplot2 Extension for Plotting Unimodal Distributions. R package version 1.0.1.",
13 | "https://github.com/iamamutt/ggdistribute/.")
14 | )
15 |
--------------------------------------------------------------------------------
/man/GeomPosterior.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/geom_posterior.R, R/ggdistribute-package.R,
3 | % R/stat_posterior_density.R
4 | \name{geom_posterior}
5 | \alias{geom_posterior}
6 | \alias{GeomPosterior}
7 | \alias{stat_density_ci}
8 | \title{Geom for plotting posterior distributions}
9 | \usage{
10 | geom_posterior(mapping = NULL, data = NULL, stat = "DensityCI",
11 | position = "spread", ..., draw_ci = TRUE, draw_sd = TRUE,
12 | midline = "#767698", brighten = TRUE, mirror = FALSE,
13 | interp_thresh = NULL, na.rm = FALSE, show.legend = NA,
14 | inherit.aes = TRUE)
15 |
16 | stat_density_ci(mapping = NULL, data = NULL, geom = "Posterior",
17 | position = "spread", ..., center_stat = "median", ci_width = 0.9,
18 | interval_type = "ci", bw = "nrd0", adjust = 1,
19 | kernel = "gaussian", cut = 1, n = 1024, trim = 0.01,
20 | na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
21 | }
22 | \arguments{
23 | \item{mapping}{Set of aesthetic mappings created by \code{\link[=aes]{aes()}} or
24 | \code{\link[=aes_]{aes_()}}. If specified and \code{inherit.aes = TRUE} (the
25 | default), it is combined with the default mapping at the top level of the
26 | plot. You must supply \code{mapping} if there is no plot mapping.}
27 |
28 | \item{data}{The data to be displayed in this layer. There are three
29 | options:
30 |
31 | If \code{NULL}, the default, the data is inherited from the plot
32 | data as specified in the call to \code{\link[=ggplot]{ggplot()}}.
33 |
34 | A \code{data.frame}, or other object, will override the plot
35 | data. All objects will be fortified to produce a data frame. See
36 | \code{\link[=fortify]{fortify()}} for which variables will be created.
37 |
38 | A \code{function} will be called with a single argument,
39 | the plot data. The return value must be a \code{data.frame}, and
40 | will be used as the layer data.}
41 |
42 | \item{stat}{Used to override the default connection between \code{geom_posterior}
43 | and \code{stat_density_ci}.}
44 |
45 | \item{position}{Position adjustment, either as a string, or the result of
46 | a call to a position adjustment function.}
47 |
48 | \item{...}{Other arguments passed on to \code{\link[=layer]{layer()}}. These are
49 | often aesthetics, used to set an aesthetic to a fixed value, like
50 | \code{colour = "red"} or \code{size = 3}. They may also be parameters
51 | to the paired geom/stat.}
52 |
53 | \item{draw_ci}{\emph{geom}. Toggles drawing of the confidence interval lines and
54 | segments.}
55 |
56 | \item{draw_sd}{\emph{geom}. Toggles drawing of the standard deviation interval
57 | lines and segments.}
58 |
59 | \item{midline}{\emph{geom}. Color of the vertical, center line. Set to \code{NA}
60 | to omit the line.}
61 |
62 | \item{brighten}{\emph{geom}. Numeric adjustments to the fill color. A value above
63 | 1 increases brightness, below decreases. Should be of length 1 or 5,
64 | otherwise values are recycled}
65 |
66 | \item{mirror}{\emph{geom}. Show standard densities (\code{mirror=FALSE}) or horizontal
67 | violin densities (\code{mirror=TRUE}).}
68 |
69 | \item{interp_thresh}{\emph{geom}. If the number of samples used to estimate the
70 | density is low, this will result in gaps between segments. This argument
71 | decides to interpolate points based on gap proportion for a segment.}
72 |
73 | \item{na.rm}{If \code{FALSE}, the default, missing values are removed with
74 | a warning. If \code{TRUE}, missing values are silently removed.}
75 |
76 | \item{show.legend}{logical. Should this layer be included in the legends?
77 | \code{NA}, the default, includes if any aesthetics are mapped.
78 | \code{FALSE} never includes, and \code{TRUE} always includes.
79 | It can also be a named logical vector to finely select the aesthetics to
80 | display.}
81 |
82 | \item{inherit.aes}{If \code{FALSE}, overrides the default aesthetics,
83 | rather than combining with them. This is most useful for helper functions
84 | that define both data and aesthetics and shouldn't inherit behaviour from
85 | the default plot specification, e.g. \code{\link[=borders]{borders()}}.}
86 |
87 | \item{geom}{Use to override the default connection between \code{geom_posterior}
88 | and \code{stat_density_ci}}
89 |
90 | \item{center_stat}{\emph{stat}. character string of method to compute the
91 | distribution's central tendency, such as \code{"median"}, \code{"mean"}, or \code{"mode"}.}
92 |
93 | \item{ci_width}{\emph{stat}. Width of the distribution's confidence/highest
94 | density interval, e.g., 0.95}
95 |
96 | \item{interval_type}{\emph{stat}. method of computing the interval, either \code{"hdi"}
97 | or \code{"ci"}}
98 |
99 | \item{bw}{The smoothing bandwidth to be used. If numeric, the standard
100 | deviation of the smoothing kernel. If character, a rule to choose the
101 | bandwidth, as listed in \link[stats:bandwidth]{stats::bandwidth}. If the bandwidth character
102 | starts wit a \code{"."} (e.g., \code{".nrd0"}), then the average bandwidth will be
103 | calculated among all groups in a panel and used for each density estimate.}
104 |
105 | \item{adjust}{A multiplicate bandwidth adjustment. This makes it possible
106 | to adjust the bandwidth while still using the a bandwidth estimator.
107 | For example, \code{adjust = 1/2} means use half of the default bandwidth.}
108 |
109 | \item{kernel}{Kernel. See list of available kernels in \code{\link[=density]{density()}}.}
110 |
111 | \item{cut}{The values to use for the start and end of the density estimation
112 | are \code{cut} bandwidths (e.g., \code{0.5*bw}) \emph{beyond} the extremes of the data.
113 | This allows the estimated density to drop to approximately zero at the
114 | extremes.}
115 |
116 | \item{n}{number of equally spaced points at which the density is to be
117 | estimated, should be a power of two, see \code{\link[=density]{density()}} for
118 | details}
119 |
120 | \item{trim}{If a value between 0 and 1 is given, trim the tails of \code{x} by
121 | some proportion according to \code{trim}. If \code{NULL} or \code{NA}, don't trim the
122 | tails. See \code{\link[=trim_ends]{trim_ends()}}.}
123 | }
124 | \description{
125 | This geom may be used to plot the density of any type of numeric variable but
126 | the displayed intervals may not be informative if the distribution deviates
127 | too much from a unimodal, symmetric distribution.
128 | }
129 | \section{Functions}{
130 | \itemize{
131 | \item \code{geom_posterior}: geom_posterior Posterior Geom
132 |
133 | \item \code{stat_density_ci}: stat_density_ci Computes a distribution density and
134 | confidence intervals for each group
135 | }}
136 |
137 | \section{Aesthetics}{
138 |
139 |
140 | \code{geom_posterior} understands the following aesthetics (required aesthetics
141 | are in bold):
142 | \itemize{
143 | \item \strong{x}
144 | \item \strong{y}
145 | \item xmin
146 | \item xmax
147 | \item alpha - colour
148 | \item fill
149 | \item group
150 | \item linetype
151 | \item size
152 | \item weight
153 | }
154 | }
155 |
156 | \section{Computed Variables}{
157 |
158 |
159 | \emph{stat_density_ci}:
160 | \itemize{
161 | \item density: density estimate from \link[stats:density]{stats::density}
162 | \item scaled: Normalized density values: \code{density / max(density)}
163 | \item count: Number of samples at density level: \code{(density / sum(density)) * n}
164 | \item xmin: minimum value of \code{x} from the data
165 | \item cil: cil cutoff value based on \code{ci_width}
166 | \item sdl: central value minus 1 sd of \code{x}
167 | \item mid: value of central tendency
168 | \item sdu: central value plus 1 sd of \code{x}
169 | \item ciu: ciu cutoff value based on \code{ci_width}
170 | \item xmax: maximum value of \code{x} from the data
171 | }
172 |
173 | \emph{position_spread}
174 | \itemize{
175 | \item ymin: minimum value of \code{y} for each group in a panel.
176 | \item ymax: maximum value of \code{y} for each group in a panel.
177 | }
178 | }
179 |
180 | \examples{
181 | \donttest{
182 | library(ggplot2)
183 |
184 | x <- data_normal_sample(mu = c(-1, 0, 1), n = 500)
185 |
186 | p <- ggplot(x, aes(x = value))
187 |
188 | p + geom_posterior()
189 |
190 | p + geom_posterior(aes(y = Condition))
191 |
192 | p + geom_posterior(aes(y = GroupScore, fill = Condition))
193 |
194 | p + geom_posterior(aes(y = GroupScore, fill = Group),
195 | brighten = c(1.3, 0, -1.3),
196 | position = position_spread(
197 | height=0.5,
198 | padding = 0))
199 |
200 | }
201 | }
202 |
--------------------------------------------------------------------------------
/man/annotate_corner.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/theme.R
3 | \name{annotate_corner}
4 | \alias{annotate_corner}
5 | \title{Write text to one of four corners of a plot}
6 | \usage{
7 | annotate_corner(text, pos = "tl", geom = c("text", "label"), ...)
8 | }
9 | \arguments{
10 | \item{text}{character string}
11 |
12 | \item{pos}{character of \code{"tl"}, \code{"tr"}, \code{"bl"}, \code{"br"} to
13 | indicate position (you may also use the full names, \code{"bottomleft"}, etc...)}
14 |
15 | \item{geom}{"text" or "label" geoms}
16 |
17 | \item{...}{additional options passed to \link[ggplot2:geom_label]{ggplot2::geom_label}}
18 | }
19 | \value{
20 | ggplot layer
21 | }
22 | \description{
23 | Write text to one of four corners of a plot
24 | }
25 | \details{
26 | If multiple panels, will write to all panels.
27 | }
28 | \examples{
29 | posterior_plot() + annotate_corner("Hi.", "bottomright")
30 | }
31 |
--------------------------------------------------------------------------------
/man/cmode.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/stats.R
3 | \name{cmode}
4 | \alias{cmode}
5 | \title{Mode from counting frequency}
6 | \usage{
7 | cmode(x)
8 | }
9 | \arguments{
10 | \item{x}{an integer vector}
11 | }
12 | \value{
13 | scalar integer value
14 | }
15 | \description{
16 | Finds the most frequent value from a vector of discrete values
17 | }
18 | \examples{
19 | cmode(rpois(1000, 20))
20 | }
21 |
--------------------------------------------------------------------------------
/man/data_normal_sample.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/data.R
3 | \name{data_normal_sample}
4 | \alias{data_normal_sample}
5 | \title{Testing dataset of grouped Normal distributions}
6 | \usage{
7 | data_normal_sample(mu = c(-0.5, 4), n = 500L, sd_range = c(0.6, 1.4),
8 | seed = 19850519)
9 | }
10 | \arguments{
11 | \item{mu}{Means for each group. A \link{numeric} vector with the length
12 | corresponding to the number of groups.}
13 |
14 | \item{n}{Number of observations for each group. Length 1 \link{integer}.}
15 |
16 | \item{sd_range}{The min and max to use for standard deviations. Length 2}
17 |
18 | \item{seed}{A seed value to generate the same sample. \link{numeric} vector.}
19 | }
20 | \value{
21 | A \link{data.frame} with the following variables: \code{Group}, \code{Condition},
22 | \code{value}.
23 | }
24 | \description{
25 | Testing dataset of grouped Normal distributions
26 | }
27 | \examples{
28 | data_normal_sample(0, 100)
29 | }
30 |
--------------------------------------------------------------------------------
/man/dmode.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/stats.R
3 | \name{dmode}
4 | \alias{dmode}
5 | \title{Mode from density estimation}
6 | \usage{
7 | dmode(x, adjust = 1.5)
8 | }
9 | \arguments{
10 | \item{x}{Value vector. Numeric or integers.}
11 |
12 | \item{adjust}{Bandwidth adjustment. See \link{density}.}
13 | }
14 | \description{
15 | Finds the mode using the \link{density} function and then obtains the maximum value.
16 | }
17 | \examples{
18 | x <- rchisq(1000, 3)
19 | hist(x, br=50)
20 | abline(v = dmode(x), col = "red")
21 | abline(v = median(x), col = "green")
22 | abline(v = mean(x), col = "blue")
23 | }
24 |
--------------------------------------------------------------------------------
/man/example_plot.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/ggdistribute-package.R
3 | \name{example_plot}
4 | \alias{example_plot}
5 | \title{Print an example of the package functions}
6 | \usage{
7 | example_plot()
8 | }
9 | \description{
10 | Print an example of the package functions
11 | }
12 |
--------------------------------------------------------------------------------
/man/figures/README-candy_wrappers-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iamamutt/ggdistribute/3efffa1ebfe20b6d7adf675412a7833b9feb8c04/man/figures/README-candy_wrappers-1.png
--------------------------------------------------------------------------------
/man/figures/README-rainbow_hills-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iamamutt/ggdistribute/3efffa1ebfe20b6d7adf675412a7833b9feb8c04/man/figures/README-rainbow_hills-1.png
--------------------------------------------------------------------------------
/man/figures/README-space_ships-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iamamutt/ggdistribute/3efffa1ebfe20b6d7adf675412a7833b9feb8c04/man/figures/README-space_ships-1.png
--------------------------------------------------------------------------------
/man/figures/README-turtle_snails-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iamamutt/ggdistribute/3efffa1ebfe20b6d7adf675412a7833b9feb8c04/man/figures/README-turtle_snails-1.png
--------------------------------------------------------------------------------
/man/ggdistribute-package.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/ggdistribute-package.R
3 | \docType{package}
4 | \name{ggdistribute-package}
5 | \alias{ggdistribute-package}
6 | \title{A 'ggplot2' Extension for Plotting Unimodal Distributions}
7 | \description{
8 | The \code{ggdistribute} package is an extension for plotting posterior or other
9 | types of unimodal distributions that require overlaying information about a
10 | distribution's intervals. It makes use of the \code{ggproto} system to extend
11 | \code{ggplot2}, providing additional "geoms", "stats", and "positions." The
12 | extensions integrate with existing \code{ggplot2} layer elements.
13 | }
14 | \details{
15 | Displaying the distributions relies heavily on stacking distributions using
16 | position_spread, which may not align with other geoms.
17 | }
18 | \seealso{
19 | \link[ggplot2:geom_density]{ggplot2::geom_density}, \link[ggplot2:position_dodge]{ggplot2::position_dodge}
20 |
21 | See \code{help(package = "ggdistribute")} for a list of functions.
22 |
23 | View vignettes with \code{browseVignettes(package ="ggdistribute")}.
24 | }
25 |
--------------------------------------------------------------------------------
/man/hdi.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/stats.R
3 | \name{hdi}
4 | \alias{hdi}
5 | \title{Highest density interval}
6 | \usage{
7 | hdi(x, prob = 0.95, warn = TRUE)
8 | }
9 | \arguments{
10 | \item{x}{Numeric vector of a distribution of data, typically a posterior
11 | sample}
12 |
13 | \item{prob}{Width of the interval from some distribution. Defaults to \code{0.95}.}
14 |
15 | \item{warn}{Option to turn off multiple sample warning message Must be in the
16 | range of \code{[0,1]}.}
17 | }
18 | \value{
19 | Numeric range
20 | }
21 | \description{
22 | This is a function that will calculate the highest density interval from a
23 | posterior sample.
24 | }
25 | \details{
26 | The default is to calcualte the highest 95 percent interval. It can be used
27 | with any numeric vector instead of having to use one of the specific MCMC
28 | classes. This function has been adapted from John K. Kruschke (2011). Doing
29 | Bayesian Data Analaysis: A Tutorial with R and BUGS.
30 | }
31 | \examples{
32 | x <- qnorm(seq(1e-04, .9999, length.out=1001))
33 | hdi_95 <- hdi(x, .95)
34 | hdi_50 <- hdi(x, .50)
35 |
36 | hist(x, br=50)
37 | abline(v=hdi_95, col="red")
38 | abline(v=hdi_50, col="green")
39 |
40 | x <- exp(seq(pi * (1 - (1/16)), pi, len = 1000))
41 | x <- c(x, rev(x)[-1])
42 | x <- c(-x, x)
43 | plot(sort(x), type="l")
44 | plot(density(x, adjust=0.25))
45 | abline(v=hdi(x, p=.49), col=2)
46 | abline(v=hdi(x, p=.50), col=3)
47 | }
48 |
--------------------------------------------------------------------------------
/man/label_plot.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/theme.R
3 | \name{label_plot}
4 | \alias{label_plot}
5 | \title{Add labels to existing plot}
6 | \usage{
7 | label_plot(labels, x, y, g = list(fontsize = 14, fontface = "bold"), ...)
8 | }
9 | \arguments{
10 | \item{labels}{character vector of labels to use}
11 |
12 | \item{x}{horz positions of items in \code{labels}}
13 |
14 | \item{y}{vert positions of items in \code{labels}}
15 |
16 | \item{g}{list of options passed to \link[grid:gpar]{grid::gpar}}
17 |
18 | \item{...}{optional args passed to \link[grid:grid.text]{grid::grid.text}}
19 | }
20 | \value{
21 | NULL. prints to current graphics device.
22 | }
23 | \description{
24 | Uses a normalized coordinate system to add text anywhere on the current plot.
25 | }
26 | \examples{
27 | example_plot()
28 | label_plot(c('a label', 'another one'), c(.1, .9), c(.95, .1))
29 |
30 | # use extra options from grid::grid.text
31 | label_plot('last one', 0.5, 0.5, just='center')
32 | }
33 | \seealso{
34 | \link[grid:grid.text]{grid::grid.text}, \link[grid:gpar]{grid::gpar}
35 | }
36 |
--------------------------------------------------------------------------------
/man/mejr_geom_defaults.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/theme.R
3 | \name{mejr_geom_defaults}
4 | \alias{mejr_geom_defaults}
5 | \title{Setup defaults for specific geoms}
6 | \usage{
7 | mejr_geom_defaults(base_size = 11, black = 51, gray = 214, lty = 3,
8 | lwd = base_size/20, cex = base_size/9, stroke = base_size * 0.05,
9 | alpha = 0.5, pch = 21, txt = base_size/4, reset = FALSE)
10 | }
11 | \arguments{
12 | \item{base_size}{base font size}
13 |
14 | \item{black}{Values from 0 to 255, indicating the darkest line and
15 | text colors (255).}
16 |
17 | \item{gray}{gray color value (0-255)}
18 |
19 | \item{lty}{linetype}
20 |
21 | \item{lwd}{linewidth}
22 |
23 | \item{cex}{point size}
24 |
25 | \item{stroke}{stroke width}
26 |
27 | \item{alpha}{alpha}
28 |
29 | \item{pch}{point shape}
30 |
31 | \item{txt}{text size}
32 |
33 | \item{reset}{reset all back to default}
34 | }
35 | \description{
36 | Setup defaults for specific geoms
37 | }
38 | \examples{
39 | # This will change the point size and shape for
40 | # all geoms in which GeomPoint inherits from.
41 | mejr_geom_defaults(cex = 1.1, pch = 19)
42 |
43 | # Reset defaults back to their original state.
44 | mejr_geom_defaults(reset=TRUE)
45 | }
46 |
--------------------------------------------------------------------------------
/man/mejr_palette.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/theme.R
3 | \name{mejr_palette}
4 | \alias{mejr_palette}
5 | \title{theme_mejr color mejr_palette}
6 | \usage{
7 | mejr_palette()
8 | }
9 | \value{
10 | list
11 | }
12 | \description{
13 | theme_mejr color mejr_palette
14 | }
15 | \examples{
16 | mejr_palette()
17 | }
18 |
--------------------------------------------------------------------------------
/man/position_spread.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/position_spread.R
3 | \name{position_spread}
4 | \alias{position_spread}
5 | \title{Spread Overlapping Grobs Spread overlapping groups by shrinking them to fit
6 | within the data's \code{y} range.}
7 | \usage{
8 | position_spread(height = NULL, reverse = FALSE, padding = 0.2)
9 | }
10 | \arguments{
11 | \item{height}{One of \code{total} (default), \code{panel}, \code{single}, a numeric scalar
12 | value to give all geoms equal space, or a numeric vector the length of
13 | \code{panels*groups} for manually specifying the height of each group.}
14 |
15 | \item{reverse}{Reverse the order of segments within overlapping \code{y} ranges.}
16 |
17 | \item{padding}{Multiple of height. Will shrink/enlarge groups to fit within a
18 | region.}
19 | }
20 | \description{
21 | Spread Overlapping Grobs Spread overlapping groups by shrinking them to fit
22 | within the data's \code{y} range.
23 | }
24 | \examples{
25 | library(ggplot2)
26 |
27 | x <- data.frame(y = rnorm(1000), x="", myGroup=sample(1:3, 1000, TRUE))
28 |
29 | ggplot(x, aes(x, y))+
30 | geom_point(aes(group=myGroup), position=position_spread(height = 0.5))
31 | }
32 |
--------------------------------------------------------------------------------
/man/post_int.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/stats.R
3 | \name{post_int}
4 | \alias{post_int}
5 | \title{Posterior intervals}
6 | \usage{
7 | post_int(x, mid = c("median", "mean", "mode"), int = c("hdi", "ci"),
8 | widths = c(0.5, 0.95), adj = 1.5, rope = NULL, warn = FALSE)
9 | }
10 | \arguments{
11 | \item{x}{Vector of numeric values. Typically a posterior sample.}
12 |
13 | \item{mid}{Central tendency estimator. Defaults to \code{"median"}. Other options
14 | include \code{"mean"} and \code{"mode"}.}
15 |
16 | \item{int}{interval type, either "hdi" or "ci"}
17 |
18 | \item{widths}{interval widths}
19 |
20 | \item{adj}{Bandwidth adjustment used only with the \code{"mode"} estimator. See
21 | \link{dmode}.}
22 |
23 | \item{rope}{Region of practical equivalence. Check how much of the
24 | distribution is within rope value.}
25 |
26 | \item{warn}{Turn off warning for flat intervals found (multiple possible
27 | values)}
28 | }
29 | \value{
30 | data.table
31 | }
32 | \description{
33 | Returns cutoff points from a posterior distribution
34 | }
35 | \examples{
36 | x <- rpois(5000, 15)
37 | ints <- post_int(x, warn = FALSE)
38 | hist(x, br=50)
39 | abline(v=ints$c, col="cyan")
40 | abline(v=ints[, c("l.wide", "r.wide")], col="magenta")
41 |
42 | post_int(x, "median", warn = FALSE)
43 | post_int(x, "mean", warn = FALSE)
44 | post_int(x, "mode", adj=2, rope = c(14, 16), warn = FALSE)
45 | }
46 |
--------------------------------------------------------------------------------
/man/posterior_plot.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/gghelpers.R
3 | \name{posterior_plot}
4 | \alias{posterior_plot}
5 | \title{Print a small example plot with geom_posterior}
6 | \usage{
7 | posterior_plot(data, x, y = "..count..", ...)
8 | }
9 | \arguments{
10 | \item{data}{A dataset to use, called at the top layer within \code{ggplot}.}
11 |
12 | \item{x}{A character string of the \code{x} axis variable name (e.g., values
13 | making up the distribution).}
14 |
15 | \item{y}{A grouping variable for generating groups of distributions. Defaults
16 | to \code{..count..} for no groups and displays the density as counts of the
17 | number of samples for the value of \code{x}.}
18 |
19 | \item{...}{Additional arguments passed to \code{\link[=geom_posterior]{geom_posterior()}}.}
20 | }
21 | \value{
22 | Object of class \code{gg}, \code{ggplot}.
23 | }
24 | \description{
25 | Print a small example plot with geom_posterior
26 | }
27 | \examples{
28 | # Generate a basic example plot if no data is specified.
29 | posterior_plot()
30 | }
31 |
--------------------------------------------------------------------------------
/man/scale_add.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/gghelpers.R
3 | \name{scale_add}
4 | \alias{scale_add}
5 | \title{scale and add}
6 | \usage{
7 | scale_add(base_size, amount = 1, adj = 0)
8 | }
9 | \arguments{
10 | \item{base_size}{start value}
11 |
12 | \item{amount}{multiple by}
13 |
14 | \item{adj}{add after}
15 | }
16 | \value{
17 | numeric
18 | }
19 | \description{
20 | scale and add
21 | }
22 |
--------------------------------------------------------------------------------
/man/show_colors.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/gghelpers.R
3 | \name{show_colors}
4 | \alias{show_colors}
5 | \title{plot and show hex values of colors}
6 | \usage{
7 | show_colors(colors, show.legend = TRUE, ncols = NULL, alpha = NA)
8 | }
9 | \arguments{
10 | \item{colors}{character vector of hex value colors}
11 |
12 | \item{show.legend}{show the legend with hex values (logical)}
13 |
14 | \item{ncols}{number of columns in the plot}
15 |
16 | \item{alpha}{set alpha level for all colors}
17 | }
18 | \value{
19 | A plot with the index of the color in the tile
20 | }
21 | \description{
22 | plot and show hex values of colors
23 | }
24 | \examples{
25 | show_colors(mejr_palette())
26 | show_colors(topo.colors(25))
27 | show_colors(cm.colors(64), FALSE)
28 | show_colors(viridisLite::viridis(15), alpha = .8)
29 | }
30 |
--------------------------------------------------------------------------------
/man/sre.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/data.R
3 | \docType{data}
4 | \name{sre}
5 | \alias{sre}
6 | \alias{sre_data}
7 | \title{Raw SRE dataset}
8 | \format{Dataset is an object of class \link[tibble:tibble]{tibble::tibble}.}
9 | \usage{
10 | sre
11 |
12 | sre_data(n = 1000, seed = 19850519)
13 | }
14 | \arguments{
15 | \item{n}{number of samplers per effect and contrast}
16 |
17 | \item{seed}{set.seed number}
18 | }
19 | \value{
20 | A dataset of \link[tibble:tibble]{tibble::tibble}.
21 | }
22 | \description{
23 | Raw SRE dataset
24 | }
25 | \section{Functions}{
26 | \itemize{
27 | \item \code{sre_data}: create samples from sre data
28 | }}
29 |
30 | \examples{
31 | sre
32 |
33 | sre_data()
34 | }
35 | \seealso{
36 | \code{\link[=sre_data]{sre_data()}}
37 | }
38 | \keyword{datasets}
39 |
--------------------------------------------------------------------------------
/man/test_mejr_theme.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/theme.R
3 | \name{test_mejr_theme}
4 | \alias{test_mejr_theme}
5 | \title{Test theme by printing plots to pdf and viewport}
6 | \usage{
7 | test_mejr_theme(w = 6.875, h = 4.5, eplot = list(), mejr = list(),
8 | gg = theme(), print = TRUE, with_test_theme = FALSE, dir)
9 | }
10 | \arguments{
11 | \item{w}{pdf width (inches)}
12 |
13 | \item{h}{pdf height (inches)}
14 |
15 | \item{eplot}{list of options for \code{example_plot}}
16 |
17 | \item{mejr}{list of options for \code{theme_mejr(...)}}
18 |
19 | \item{gg}{further theme customization with ggplot::theme(...)}
20 |
21 | \item{print}{show the \code{eplot} plot}
22 |
23 | \item{with_test_theme}{also print the same plot using \code{ggplot2::theme_test}}
24 |
25 | \item{dir}{directory where to save temp pdf files, such as tempdir()}
26 | }
27 | \description{
28 | Test theme by printing plots to pdf and viewport
29 | }
30 |
--------------------------------------------------------------------------------
/man/theme_mejr.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/theme.R
3 | \name{theme_mejr}
4 | \alias{theme_mejr}
5 | \title{Custom ggplot2 theme}
6 | \usage{
7 | theme_mejr(base_size = 11,
8 | base_family = getOption("ggdistribute.font"), black = 67,
9 | margin_add = 2, debug = FALSE, FUN = NULL, ...)
10 | }
11 | \arguments{
12 | \item{base_size}{base font size}
13 |
14 | \item{base_family}{base font family}
15 |
16 | \item{black}{Values from 0 to 255, indicating the darkest line and
17 | text colors (255).}
18 |
19 | \item{margin_add}{additive adjustment of margin spacing and tick length (in "pt"
20 | units). May be positive or negative.}
21 |
22 | \item{debug}{Add debug info to text.}
23 |
24 | \item{FUN}{Call a function before returning the theme elements.}
25 |
26 | \item{...}{Arguments passed to \code{FUN}}
27 | }
28 | \description{
29 | A complete, minimal theme to be used with the \code{ggplot2} package
30 | }
31 | \details{
32 | You can use \code{theme_update} to change some aspect of this theme after
33 | using \code{theme_set}.
34 | }
35 | \examples{
36 | \donttest{
37 | library(ggplot2)
38 |
39 | theme_set(theme_mejr(debug = TRUE))
40 | example_plot()
41 |
42 | theme_set(theme_mejr())
43 | theme_update(axis.text = element_blank()) # any updates can go here
44 | example_plot()
45 | }
46 | }
47 | \seealso{
48 | \link{mejr_geom_defaults}, \link[ggplot2:theme_update]{ggplot2::theme_update}, \link[ggplot2:theme_set]{ggplot2::theme_set}
49 | }
50 |
--------------------------------------------------------------------------------
/man/trim_ends.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/stats.R
3 | \name{trim_ends}
4 | \alias{trim_ends}
5 | \title{Trim extreme values at each end of a vector.}
6 | \usage{
7 | trim_ends(x, trim = 0.05, na.rm = TRUE)
8 | }
9 | \arguments{
10 | \item{x}{A \link{numeric} vector}
11 |
12 | \item{trim}{Proportion of vector length to trim. Must be between 0 and 1.
13 | E.g., a value 0.05 (default) trims 2.5\% off each end of a sorted vector.}
14 |
15 | \item{na.rm}{omit \code{NA} values. May result in different size vector.}
16 | }
17 | \value{
18 | A \link{numeric} vector in the original order of \code{x}, but with trimmed
19 | values as \code{NA} if \code{na.rm=TRUE} or with these values removed if \code{FALSE}
20 | (which will result in a different sized vector from the input).
21 | }
22 | \description{
23 | Trim extreme values at each end of a vector.
24 | }
25 | \examples{
26 | x <- rgamma(10000, 1, 1)
27 | range(x)
28 | length(x) # <- 10000
29 | sum(is.na(x)) # <- 0
30 |
31 | t <- trim_ends(x, trim = 0.1)
32 | range(t)
33 | length(t) # <- 9000
34 | sum(is.na(t)) # <- 0
35 |
36 | t <- trim_ends(x, 0.1, na.rm = FALSE)
37 | range(t, na.rm = TRUE)
38 | length(t) # <- 10000
39 | sum(is.na(t)) # <- 1000
40 | }
41 |
--------------------------------------------------------------------------------
/tests/testthat.R:
--------------------------------------------------------------------------------
1 | library(testthat)
2 | library(ggdistribute)
3 |
4 | test_check("ggdistribute")
5 |
--------------------------------------------------------------------------------
/tests/testthat/test_geom_posterior.R:
--------------------------------------------------------------------------------
1 | library(ggdistribute)
2 | library(ggplot2)
3 | context("Testing geom posterior")
4 |
5 | test_that("Identity stat", {
6 | dt <- ggdistribute:::ggdist_data()
7 | d <- stats::density(dt$value, n=nrow(dt))
8 | dt$dx <- d$x
9 | dt$dy <- d$y
10 | dt$mid <- 4
11 |
12 | expect_s3_class(
13 | ggplot(dt, aes(x=dx, y=dy)) +
14 | geom_posterior(
15 | stat="identity", position="identity",
16 | draw_ci=FALSE, draw_sd=FALSE, aes(mid=mid)
17 | ) #
18 | , c("gg", "ggplot")
19 | )
20 | })
21 |
--------------------------------------------------------------------------------
/tests/testthat/test_position_spread.R:
--------------------------------------------------------------------------------
1 | library(ggdistribute)
2 | library(data.table)
3 | context("Testing position spread")
4 |
5 | test_that("Overlaps", {
6 | y_vals <- matrix(c(
7 | 0, 1, 1, 2.5, 1.1, 2.5, 3, 4.9,
8 | 4, 5, 4.7, 5.5, 5.49999, 5.5
9 | ), nrow = 2)
10 |
11 | data <- data.table(
12 | group = as.integer(seq_len(ncol(y_vals))),
13 | PANEL = rep(1L, ncol(y_vals))
14 | )
15 | data <- data[
16 | , .(y = seq(y_vals[1L, group],
17 | y_vals[2L, group],
18 | length.out = 3)),
19 | .(PANEL, group)
20 | ]
21 | data[group == max(group), group := group + 2L]
22 |
23 | o <- ggdistribute:::get_overlaps(data, "y", tol = -1e-3)
24 | expect_identical(which(o$overlap), c(7L, 16L))
25 | expect_identical(which(o$within), c(7L, 21L))
26 |
27 | o <- ggdistribute:::get_overlaps(data[group == 9], "y", tol = -1e-3)
28 | expect_true(is.na(o$space))
29 | })
30 |
--------------------------------------------------------------------------------
/tests/testthat/test_stat_density.R:
--------------------------------------------------------------------------------
1 | library(ggdistribute)
2 | context("Testing stat density computations")
3 |
4 | set.seed(20130110)
5 | x <- rnorm(1000, 100, 15)
6 |
7 | test_that("List modification", {
8 | expect_named(compute_density(x), c(
9 | "x", "density", "scaled",
10 | "count", "n"
11 | ))
12 |
13 | defaults <- compute_conf_ints(x)
14 |
15 | expect_named(defaults, c("mid", "sdl", "sdu", "cil", "ciu"))
16 | expect_identical(defaults, compute_conf_ints(x, NA, NA, NA))
17 | })
18 |
--------------------------------------------------------------------------------
/vignettes/geom_posterior.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Plotting Posterior Distributions with `ggdistribute`"
3 | author: "Joseph M. Burling"
4 | date: "`r Sys.Date()`"
5 | output: rmarkdown::html_vignette
6 | vignette: >
7 | %\VignetteIndexEntry{GeomPosterior}
8 | %\VignetteEngine{knitr::rmarkdown}
9 | %\VignetteEncoding{UTF-8}
10 | ---
11 |
12 | ```{r setup, include = FALSE, warning=FALSE, message=FALSE}
13 | knitr::opts_chunk$set(
14 | collapse = TRUE,
15 | comment = "#>",
16 | strip.white = FALSE,
17 | tidy = FALSE,
18 | fig.align = "center",
19 | dpi = 300,
20 | fig.width = 5.25,
21 | fig.height = 3.8,
22 | out.width = "90%"
23 | )
24 | ```
25 |
26 | ```{r load-and-opts, echo=FALSE, message=FALSE}
27 | library(ggplot2)
28 | theme_set(theme_gray(10))
29 | ```
30 |
31 | # Introduction
32 |
33 | The `ggdistribute` package is an extension for plotting posterior or other types of unimodal distributions that require overlaying information about a distribution's intervals. It makes use of the `ggproto` system to extend `ggplot2`, providing additional "geoms", "stats", and "positions." The extensions integrate with existing `ggplot2` layer elements.
34 |
35 | To load the package to access the exported `ggplot2` extensions, do the following,
36 |
37 | ```{r load-ggdistribute}
38 | library(ggdistribute)
39 | ```
40 |
41 | The `data` object below is a randomly generated dataset of 5 different normal distributions. Two factors `Condition` and `Group` are assigned according to the generated values. 1000 samples are generated for each value of `mu`.
42 |
43 | ```{r make-data}
44 | data <- data_normal_sample(mu = c(-1, 0, 2, 5, 10), n = 1000)
45 | ```
46 |
47 | # Extensions passed to `ggplot2::layer`
48 |
49 | ## `geom_posterior(...)`, `GeomPosterior`
50 |
51 | This is the main function wrapper to generate the posterior distribution grobs. See `help("geom_posterior")` for a list of options passed to the ggproto object `GeomPosterior`. The `geom_posterior()` function with no arguments and no `y` aesthetic defaults to estimating the normalized density (integerates to 1) times the number of data points. This is the same as `aes(y = ..count..)` with `geom_posterior`.
52 |
53 | ```{r ex1}
54 | b_cond <- data[data$Condition == "B", ]
55 |
56 | ggplot(b_cond, aes(x = value))+
57 | geom_posterior()
58 | ```
59 |
60 | If `y` is discrete, the densities are justified at the bottom of the `y` value.
61 |
62 | ```{r ex2}
63 | ggplot(data, aes(x = value, y = Condition))+
64 | geom_posterior()
65 | ```
66 |
67 | Mirroring can be turned on to generate densities similar to `geom_violin`, and `geom_posterior` can be used like other `geoms` in `ggplot2`, like specifying facetting.
68 |
69 | ```{r ex3, fig.height=6}
70 | ggplot(data, aes(x = value, y = Condition))+
71 | geom_posterior(mirror = TRUE)+
72 | facet_grid(Group~., scales = "free_y")
73 | ```
74 |
75 | ## `stat_density_ci(...)`, `StatDensityCI`
76 |
77 | The `StatDensityCI` class is the default stat for the `geom_posterior` wrapper. It computes densities for each group and finds the confidence intervals. See `help("stat_density_ci")` for additional options and computed variables.
78 |
79 | ```{r ex4}
80 | ggplot(data, aes(x = value, y = Condition)) +
81 | stat_density_ci(n = 1024, interp_thresh = .001)
82 | ```
83 |
84 | The `stat_density_ci` wrapper can also be used with other geoms that make use of `density`, `count`, and `scaled` variables.
85 |
86 | ```{r ex5}
87 | ggplot(data, aes(x = value, y = ..density.., fill = Condition)) +
88 | stat_density_ci(
89 | alpha = 0.5,
90 | n = 1024,
91 | geom = "density",
92 | position = "identity"
93 | )
94 | ```
95 |
96 | ## `position_spread(...)`, `PositionSpread`
97 |
98 | The `PositionSpread` class spreads out overlapping densities within the range of their y axis value. For instance, there are two different groups for `Condition` A-D, but only one group in E. Distributions within each `Condition` are resized and spread over the group's y interval. Padding is turned off below to see where distributions begin and end.
99 |
100 | ```{r ex6}
101 | data$Group[data$Condition == "E"] <- "z"
102 |
103 | ggplot(data, aes(x = value, y = Condition, group = Group)) +
104 | geom_posterior(position = position_spread(padding = 0)) +
105 | theme(panel.grid.major.y = element_line(color = gray(.8)))
106 | ```
107 |
108 |
109 | # Extended example
110 |
111 | The package function `example_plot()` is an overview of combining `ggdistribute` with other `ggplot2` elements. The contents of this function are printed below and gives details about the extended parts to `ggplot2`.
112 |
113 | ```{r ex-plot-print, fig.width=5, fig.height=3, out.width="100%"}
114 | # color palette
115 | colors <- mejr_palette()
116 |
117 | plt <-
118 | ggplot(sre_data(5000),
119 | aes(y=effect)) +
120 | # ggdistribute specific elements -------------------------------------------
121 | geom_posterior(
122 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
123 | # geom_posterior() aesthetics mappings
124 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125 | aes(x=value, fill=contrast),
126 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
127 | # options passed to stat_density_ci() for estimating intervals
128 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129 | interp_thresh=.001, # threshold for interpolating segment gaps
130 | center_stat="median", # measure of central tendency
131 | ci_width=0.90, # width corresponding to CI segments
132 | interval_type="ci", # quantile intervals not highest density interval
133 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
134 | # options passed to stat_density_ci() for estimating density
135 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136 | bw=".nrd0", # bandwidth estimator type
137 | adjust=1.5, # adjustment to bandwidth
138 | n=1024, # number of samples in final density
139 | trim=.005, # trim `x` this proportion before estimating density
140 | cut=1.5, # tail extension for zero density estimation
141 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142 | # geom_posterior() options
143 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
144 | draw_ci=TRUE, # toggle showing confidence interval parts
145 | draw_sd=TRUE, # toggle showing standard deviation parts
146 | mirror=FALSE, # toggle horizontal violin distributions
147 | midline=NULL, # line displaying center of dist. (NULL=aes color)
148 | brighten=c(3, 0, 1.333), # additive adjustment of segment fill colors
149 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150 | # position_spread() options
151 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 | position=position_spread(
153 | reverse=TRUE, # order of spreaded groups within panels
154 | padding=0.3, # shrink heights of distributions
155 | height="panel" # scale by heights within panels
156 | ), #
157 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158 | # standard ggplot layer options
159 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 | size=0.15, color=colors$gray, vjust=0.7, show.legend=FALSE
161 | ) +
162 | # standard ggplot2 elements ------------------------------------------------
163 | geom_vline(alpha=0.5, color=colors$gray, size=0.333, linetype=1, xintercept=0) +
164 | scale_x_continuous(breaks=seq(-1, 1, .05)) +
165 | facet_grid("contrast ~ .", scales="free_y", space="free_y") +
166 | scale_fill_manual(values=c(colors$yellow, colors$magenta, colors$cyan)) +
167 | labs(x="Difference in accuracy (posterior predictions)") +
168 | theme(
169 | legend.position="none", strip.text.y=element_text(angle=0, hjust=0.5),
170 | panel.border=element_rect(fill=NA, color=colors$lightgray, size=0.67),
171 | panel.grid=element_blank(), panel.ontop=FALSE, axis.title.y=element_blank(),
172 | plot.margin=margin(t=2, r=4, b=2, l=2, unit="pt")
173 | )
174 |
175 | plot(plt)
176 | ```
177 |
178 | ```{r other-tests, eval=FALSE, echo=FALSE}
179 | library(ggplot2)
180 |
181 | # other visual inspections
182 | dt <- ggdistribute:::ggdist_data(1000, j = 5)
183 |
184 | ggplot(dt) + aes(x = value) +
185 | geom_posterior(n = 512, interp_thresh = .001) + labs(title = "no y")
186 |
187 | ggplot(dt) + aes(x = value, y = 10) +
188 | geom_posterior(n = 512, interp_thresh = .001) + labs(title = "scalar y")
189 |
190 | ggplot(dt) + aes(x = value, y = j_discrete) +
191 | geom_posterior(n = 512, interp_thresh = .001) + labs(title = "char y")
192 |
193 | ggplot(dt) + aes(x = value, y = j_discrete, group = k_discrete) +
194 | geom_posterior(n = 512, interp_thresh = .001) +
195 | labs(title = "char y, w/ group")
196 |
197 | ggplot(dt) + aes(x = value, y = k_discrete) +
198 | geom_posterior(n = 512, interp_thresh = .001, aes(group = j_discrete)) +
199 | labs(title = "char y, w/ group switched")
200 |
201 | ggplot(dt) + aes(x = value) +
202 | geom_posterior(n = 512, interp_thresh = .001, aes(group = j_discrete)) +
203 | labs(title = "no y, w/ group")
204 |
205 | ggplot(dt) + aes(x = value, y = j_discrete) +
206 | geom_posterior(n = 512, interp_thresh = .001, aes(group = j_discrete)) +
207 | labs(title = "char y, w/ same y group")
208 |
209 | ggplot(dt) + aes(x = value, y = j_discrete) +
210 | geom_posterior(n = 512, interp_thresh = .001, aes(fill = k_discrete)) +
211 | labs(title = "char y, w/ diff group")
212 |
213 | ggplot(dt) + aes(x = value, y = I) +
214 | geom_posterior(n = 512, interp_thresh = .001, aes(group = j_discrete)) +
215 | labs(title = "integer y, w/ group")
216 |
217 | ggplot(dt) + aes(x = value, y = j_discrete) +
218 | geom_posterior(
219 | n = 512, interp_thresh = .001,
220 | position = position_spread(height = 20)) +
221 | labs(title = "manual height, w/ group")
222 |
223 | ggplot(dt) + aes(x = value, y = variable) +
224 | geom_posterior(
225 | n = 512, interp_thresh = .001,
226 | mirror = TRUE, aes(group = j_discrete)) +
227 | labs(title = "cont. y, w/ group, mirrored")
228 |
229 | ggplot(dt) + aes(x = value, y = variable * 10) +
230 | geom_posterior(
231 | n = 512, interp_thresh = .001, mirror = TRUE,
232 | aes(group = j_discrete)) + facet_wrap(~k_discrete) +
233 | labs(title = "cont. y, w/ group, wrap, mirrored")
234 |
235 | dt$k[dt$j == 1 & dt$k == 2] <- NA
236 |
237 | ggplot(dt) + aes(x = value, y = j_discrete, group = k_discrete) +
238 | geom_posterior(n = 512, interp_thresh = .001) +
239 | facet_grid(j_discrete ~ ., scales = "free_y") +
240 | labs(title = "char y, w/ group, grid, missing group")
241 |
242 | ggplot(dt) + aes(x = value, group = k_discrete) +
243 | geom_posterior(n = 512, interp_thresh = .001) +
244 | facet_grid(j_discrete ~ ., scales = "free_y") +
245 | labs(title = "no y, w/ group, grid, missing group")
246 | ```
247 |
--------------------------------------------------------------------------------