R tableGrob cell colors with condition on multiple columns - formatting

Is there a way to put colors on all the cells of a tableGrob that are not 0 ?
I have this table with a lot of lines
[][1]
[1]: https://i.stack.imgur.com/w7RCJ.png
I am using tableGrob and then grid.arrange to put 2 tables on the same page with some text
tab1<-tableGrob(tab_glob,rows=NULL,theme = ttheme_default(10),widths=unit(rep(1/ncol(tab_glob), ncol(tab_glob)), "null"), heights=unit(rep(0.95/nrow(tab_glob), nrow(tab_glob)),"npc"))
tab2<-tableGrob(Notes_tous,rows=NULL,theme = ttheme_default(11))
footnote<- textGrob("Moyenne référence = résultats techniciens référents")
padding<-unit(0.5,"line")
tab3<-gtable_add_rows(tab2,
heights = grobHeight(footnote)+ padding,pos=0)
tab3 <- gtable_add_grob(tab3,list(footnote),
t=1, l=1,
r=ncol(tab2))
pdf(paste("Table_",i,".pdf",sep = ""),width=10,height=15) #save in pdf
Point_tab<-grid.arrange(tab1,tab3,ncol=1,nrow=2, top=textGrob("\n \n \nNombre de pointages par note",gp=gpar(fontsize=14,font=3)))
dev.off()
In the first table, showing all the values, I am looking for a way to highlight the values that are not 0 in all the columns. All the answers I have found on the internet are for particular cells or a particular value... Do you have any idea to help me update my code ?
Kind regards,

Related

Why is altair single select not changing my graph?

I've tried to google why this isn't working but it doesn't appear obvious to me. Can you please tell me why the selection dropdown isn't changing the graph?
Thanks
source = data.unemployment_across_industries.url
df = data.unemployment_across_industries()
series_val = df.series.str.split(',').explode().unique().tolist()
print(series_val)
input_dropdown = alt.binding_select(options=series_val, name='Industry: ')
selection = alt.selection_single(fields=['series'], bind=input_dropdown)
fig3 = alt.Chart(source).mark_area().encode(
alt.X('yearmonth(date):T',
axis=alt.Axis(format='%Y', domain=False, tickSize=0)
),
alt.Y('sum(count):Q', stack='center', axis=None),
alt.Color('series:N',
scale=alt.Scale(scheme='category20b')
)
).add_selection(
selection
)
fig3
The selection doesn't change the graph because you have not conditioned any part of the graph on the selection (none of your encodings depend on the value of the selection, nor is the data filtered based on the selection).
Perhaps you intended to do something like this?
fig3 = alt.Chart(source).mark_area().encode(
alt.X('yearmonth(date):T',
axis=alt.Axis(format='%Y', domain=False, tickSize=0)
),
alt.Y('sum(count):Q', stack='center', axis=None),
color=alt.condition(selection,
alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
alt.value('lightgray'))
).add_selection(
selection
)
For more on how to use selections in Altair charts, see https://altair-viz.github.io/user_guide/interactions.html

replace value under column in pandas under condition

I want to replace values under column Severity with following values.
4:out for season
3:out indefinitely
2:DNP
1:DTD
but .replace doesn't seem to work. Any other ways to get around this
enter image description here
I think you have things reversed in your replacement code.
Try this out and report back what happens:
replace_dict = {'DTD':1,'DNP':2,'out indefinitely':3,'out for season':4}
df = pd.DataFrame({'severity':'out for season'},index=[0])
df['severity'] = df['severity'].replace(replace_dict)

pandas/python Merge/concatenate related data of duplicate rows and add a new column to existing data frame

I am new to Pandas, and wanted your help with data slicing.
I have a dump of 10 million rows with duplicates. Please refer to this image for a sample of the rows with the steps I am looking to perform.
As you see in the image, the column for criteria "ABC" from Source 'UK' has 2 duplicate entries in the Trg column. I need help with:
Adding a concatenated new column "All Targets" as shown in image
Removing duplicates from above table so that only unique values without duplicates appear, as shown in step 2 in the image
Any help with this regard will be highly appreciated.
I would do like this:
PART 1:
First define a function that does what you want, than use apply method:
def my_func(grouped):
all_target = grouped["Trg"].unique()
grouped["target"] = ", ".join(all_target)
return grouped
df1 = df.groupby("Criteria").apply(my_func)
#output:example with first 4 rows
Criteria Trg target
0 ABC DE DE, FR
1 ABC FR DE, FR
2 DEF UK UK, FR
3 DEF FR UK, FR
PART 2:
df2 = df1.drop_duplicates(subset=["Criteria"])
I tried it only on first 4 rows so let me know if it works.

How to change color in a column in lazyhighcharts?

I am using LazyHighCharts in rails 3. My requirement is to show different color in a column.
when i use
series = {
:type=> 'bar',
:name=> [],
:data=> #rooms,
:color=> 'pink'
}
it displays whole column in pink color. Suppose i have 5 rows in a column and i want to show first row in pink color and the rest four row in green color. can anyone suggest me solution for this.
thnks
i don't know if you have resolved this issue, but this is how i resolved it.
#Controller before set data to the series option
data = []
your_array.each do |t|
data << {:y=>t.value, :color=>"#"+("%06x" % (rand * 0xffffff))}
end
then set data to series option
f.series({:name=>"Subcurso", :data=>data} )

Matplotlib table: individual column width

Is there a way to specify the width of individual columns in a matplotlib table?
The first column in my table contains just 2-3 digit IDs, and I'd like this column to be smaller than the others, but I can't seem to get it to work.
Let's say I have a table like this:
import matplotlib.pyplot as plt
fig = plt.figure()
table_ax = fig.add_subplot(1,1,1)
table_content = [["1", "Daisy", "ill"],
["2", "Topsy", "healthy"]]
table_header = ('ID', 'Name','Status')
the_table = table_ax.table(cellText=table_content, loc='center', colLabels=table_header, cellLoc='left')
fig.show()
(Never mind the weird cropping, it doesn't happen in my real table.)
What I've tried is this:
prop = the_table.properties()
cells = prop['child_artists']
for cell in cells:
text = cell.get_text()
if text == "ID":
cell.set_width(0.1)
else:
try:
int(text)
cell.set_width(0.1)
except TypeError:
pass
The above code seems to have zero effect - the columns are still all equally wide. (cell.get_width() returns 0.3333333333, so I would think that width is indeed cell-width... so what am I doing wrong?
Any help would be appreciated!
I've been searching the web over and over again looking for similar probelm sollutions. I've found some answers and used them, but I didn't find them quite straight forward. By chance I just found the table method get_celld when simply trying different table methods.
By using it you get a dictionary where the keys are tuples corresponding to table coordinates in terms of cell position. So by writing
cellDict=the_table.get_celld()
cellDict[(0,0)].set_width(0.1)
you will simply adress the upper left cell. Now looping over rows or columns will be fairly easy.
A bit late answer, but hopefully others may be helped.
Just for completion. The column header starts with (0,0) ... (0, n-1). The row header starts with (1,-1) ... (n,-1).
---------------------------------------------
| ColumnHeader (0,0) | ColumnHeader (0,1) |
---------------------------------------------
rowHeader (1,-1) | Value (1,0) | Value (1,1) |
--------------------------------------------
rowHeader (2,-1) | Value (2,0) | Value (2,1) |
--------------------------------------------
The code:
for key, cell in the_table.get_celld().items():
print (str(key[0])+", "+ str(key[1])+"\t"+str(cell.get_text()))
Condition text=="ID" is always False, since cell.get_text() returns a Text object rather than a string:
for cell in cells:
text = cell.get_text()
print text, text=="ID" # <==== here
if text == "ID":
cell.set_width(0.1)
else:
try:
int(text)
cell.set_width(0.1)
except TypeError:
pass
On the other hand, addressing the cells directly works: try cells[0].set_width(0.5).
EDIT: Text objects have an attribute get_text() themselves, so getting down to a string of a cell can be done like this:
text = cell.get_text().get_text() # yup, looks weird
if text == "ID":