r-lib / pillar

Format columns with colour
https://pillar.r-lib.org/
Other
178 stars 38 forks source link

Guidance colorizing values within a column #655

Open jmw86069 opened 8 months ago

jmw86069 commented 8 months ago

I'm excited about this package, and am hopeful it might fit my needs.

I'm trying to colorize values within a column - I have logic, functions, methods I can use to colorize values in a column. I do not see how to apply this logic.

The simplest use case is to colorize positive numeric values blue, since negative is red. Similarly, I have categorical colors, how might I apply them to a character column?

Best guess, I need to write custom functions to override pillar:::pillar_shaft.classname() for every column class, by the class of data in each column.

Is there another way to inject color into the output?

The vignette/extensions does not describe where to inject color. The custom Body function does receive column values, however they are pillar_component objects which contain data values in the form of (undocumented) pillar_ornament object. I think these values have already been updated by a previous pillar_shaft() step.

In the vctrs package, the vignette "Printing vectors nicely in tibbles" implements a custom function deg_min_color() to demonstrate how to colorize parts of column values. This mechanism is applied to all columns of a given class. So it leads me to conclude that I need to write custom functions for each column class.

However, if I implement a custom pillar_shaft.numeric(), it misses all the fun stuff that happens inside the (hidden) pillar:::pillar_shaft_number(). Same for pillar:::pillar_shaft.character().

Finally, I see new_pillar_shaft() can accept ANSI escape codes in argument formatted, however I don't see how to provide ANSI formatting of my own.

Ideal world, I'd like to pass an optional colorization function... somewhere. :)

Thank you for any guidance!

jmw86069 commented 8 months ago

I'll be upfront, I anticipate a totally reasonable response might be "Try it and let us know if it works."

I think that's a reasonable next step, no shade.

Imagine I write custom functions pillar_shaft.numeric(), pillar_shaft.integer64(), pillar_shaft.character(), pillar_shaft.factor() I probably cover everything I could reasonable handle. If it doesn't work for some reason, then I have something concrete to post and ask.

However, if there happens to be an easier mechanism that I'm missing, then let me know if you have a few minutes. :) Or let me know there is one and I'll look harder for it. Best to you.

krlmlr commented 8 months ago

Thanks for your interest.

I can't spend time thinking deeply about it now. Have you seen https://pillar.r-lib.org/articles/printing.html?

If that doesn't help, a good way might be to implement your desired behavior in a fork of the pillar package. We could then think about how to implement this using the existing extension options.